714

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
  • 6
    Path('./doc.txt').stat().st_size Commented Dec 31, 2019 at 18:21

5 Answers 5

1017

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
Sign up to request clarification or add additional context in comments.

5 Comments

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`
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
@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
I ran both with %timeit on all the files in a given directory and found os.stat to be marginally faster (~6%).
@16num Which is just logical because os.path.getsize() does nothing else than calling os.stat().st_size.
261
os.path.getsize(path)

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

1 Comment

Just as a note for someone curious, getsize() behind the scenes does os.stat(path).st_size, which was the other approach explained here.
99

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 Comments

returns it in kb right?
No, it's in Bytes.
30

Try

os.path.getsize(filename)

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

Comments

17

You can use os.stat(path) call

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

1 Comment

You need to read the st_size attribute of the object you get back from that to get the file size.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.