How can I check file size in Python?

How can I check file size in Python?

Using os.path.getsize:

>>> import os
>>> b = os.path.getsize(/path/isa_005.mp3)
>>> b
2071611

The output is in bytes.

You need the st_size property of the object returned by os.stat. You can get it by either using pathlib (Python 3.4+):

>>> from pathlib import Path
>>> Path(somefile.txt).stat()
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> Path(somefile.txt).stat().st_size
1564

or using os.stat:

>>> import os
>>> os.stat(somefile.txt)
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> os.stat(somefile.txt).st_size
1564

Output is in bytes.

How can I check file size in Python?

The other answers work for real files, but if you need something that works for file-like objects, try this:

# f is a file-like object. 
f.seek(0, os.SEEK_END)
size = f.tell()

It works for real files and StringIOs, in my limited testing. (Python 2.7.3.) The file-like object API isnt really a rigorous interface, of course, but the API documentation suggests that file-like objects should support seek() and tell().

Edit

Another difference between this and os.stat() is that you can stat() a file even if you dont have permission to read it. Obviously the seek/tell approach wont work unless you have read permission.

Edit 2

At Jonathons suggestion, heres a paranoid version. (The version above leaves the file pointer at the end of the file, so if you were to try to read from the file, youd get zero bytes back!)

# f is a file-like object. 
old_file_position = f.tell()
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(old_file_position, os.SEEK_SET)

Leave a Reply

Your email address will not be published. Required fields are marked *