'Size of an open file object

Is there a way to find the size of a file object that is currently open?

Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.



Solution 1:[1]

Well, if the file object support the tell method, you can do:

current_size = f.tell()

That will tell you were it is currently writing. If you write in a sequential way this will be the size of the file.

Otherwise, you can use the file system capabilities, i.e. os.fstat as suggested by others.

Solution 2:[2]

If you have the file descriptor, you can use fstat to find out the size, if any. A more generic solution is to seek to the end of the file, and read its location there.

Solution 3:[3]

Another solution is using StringIO "if you are doing in-memory operations".

with open(file_path, 'rb') as x:
    body = StringIO()
    body.write(x.read())
    body.seek(0, 0)

Now body behaves like a file object with various attributes like body.read().

body.len gives the file size.

Solution 4:[4]

Nobody mentioned what to me seems the simplest way i.e using the len() function after a read:

>>> with open("C:\\path\\to\\a\\file.txt", 'rb') as f:
...     f_read = f.read()  
...     print(len(f_read))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PierreBdR
Solution 2 Chris Jester-Young
Solution 3 vestronge
Solution 4