645

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.

6966488-1
  • 6,493
  • 2
  • 13
  • 3

5 Answers5

921

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
Boris Verkhovskiy
  • 10,733
  • 7
  • 77
  • 79
Artsiom Rudzenka
  • 26,491
  • 4
  • 32
  • 51
  • 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 06 '11 at 05: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 – Artsiom Rudzenka Jul 06 '11 at 05: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 – John La Rooy Jul 06 '11 at 05: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 04 '16 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 '16 at 12:24
247
os.path.getsize(path)

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

Oscar Mederos
  • 28,017
  • 21
  • 79
  • 123
K Mehta
  • 10,083
  • 4
  • 43
  • 73
  • 3
    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 05 '20 at 21:04
96

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
kabirbaidhya
  • 2,944
  • 2
  • 33
  • 52
ZelluX
  • 63,444
  • 18
  • 69
  • 104
26

Try

os.path.getsize(filename)

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

rajasaur
  • 5,208
  • 2
  • 26
  • 22
15

You can use os.stat(path) call

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

Oscar Mederos
  • 28,017
  • 21
  • 79
  • 123
IvanGL
  • 742
  • 5
  • 21