Getting file size in Python?

PythonFileSize

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

os.path.getsize(path)

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

Solution 3 - Python

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

Solution 4 - Python

Try

os.path.getsize(filename)

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

Solution 5 - Python

You can use os.stat(path) call

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question6966488-1View Question on Stackoverflow
Solution 1 - PythonArtsiom RudzenkaView Answer on Stackoverflow
Solution 2 - PythonK MehtaView Answer on Stackoverflow
Solution 3 - PythonZelluXView Answer on Stackoverflow
Solution 4 - PythonrajasaurView Answer on Stackoverflow
Solution 5 - PythonIvanGLView Answer on Stackoverflow