681

Is there a built-in function for getting the size of a file object in bytes? I see some people do something like this:

def getSize(fileobject):
    fileobject.seek(0,2) # move the cursor to the end of the file
    size = fileobject.tell()
    return size

file = open('myfile.bin', 'rb')
print getSize(file)

But from my experience with Python, it has a lot of helper functions so I'm guessing maybe there is one built-in.

1
  • 5
    Path('./doc.txt').stat().st_size
    – user3064538
    Dec 31, 2019 at 18:21

5 Answers 5

971

Use os.path.getsize(path) which will

Return the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible.

import os
os.path.getsize('C:\\Python27\\Lib\\genericpath.py')

Or use os.stat(path).st_size

import os
os.stat('C:\\Python27\\Lib\\genericpath.py').st_size 

Or use Path(path).stat().st_size (Python 3.4+)

from pathlib import Path
Path('C:\\Python27\\Lib\\genericpath.py').stat().st_size
5
  • Thanks you all. I don't know if you can reply to all posts at once, so I'll just rply to the last answerer. I can't seem to get it to work. ` File "C:\\python\lib\genericpath.py", line 49, in getsize return os.stat(filename).st_size TypeError: stat() argument 1 must be encoded string without NULL bytes, not str`
    – 6966488-1
    Jul 6, 2011 at 5:39
  • 1
    Think you need "C:\\python\\lib\\genericpath.py" - e.g. os.path.getsize('C:\\Python27\\Lib\\genericpath.py') or os.stat('C:\\Python27\\Lib\\genericpath.py').st_size Jul 6, 2011 at 5:43
  • @696, Python will let you have NULL bytes it strings, but it doesn't make sense to pass those into getsize because the filename can't have NULL bytes in it Jul 6, 2011 at 5:45
  • 4
    I ran both with %timeit on all the files in a given directory and found os.stat to be marginally faster (~6%).
    – J'e
    Nov 4, 2016 at 16:00
  • 11
    @16num Which is just logical because os.path.getsize() does nothing else than calling os.stat().st_size.
    – Martin
    Nov 22, 2016 at 12:24
252
os.path.getsize(path)

Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.

1
  • 4
    Just as a note for someone curious, getsize() behind the scenes does os.stat(path).st_size, which was the other approach explained here.
    – Melardev
    Feb 5, 2020 at 21:04
97

You may use os.stat() function, which is a wrapper of system call stat():

import os

def getSize(filename):
    st = os.stat(filename)
    return st.st_size
2
  • returns it in kb right?
    – 3kstc
    Jun 4, 2019 at 4:46
  • 2
    No, it's in Bytes. Jun 17, 2019 at 7:28
27

Try

os.path.getsize(filename)

It should return the size of a file, reported by os.stat().

16

You can use os.stat(path) call

http://docs.python.org/library/os.html#os.stat

Not the answer you're looking for? Browse other questions tagged or ask your own question.