pythonfilesize

What’s the best way to get the file size?


There are actually three ways I have in mind to determine a files size:

  1. open and read it, and get the size of the string with len()
  2. using os.stat and getting it via st_size -> what should be the "right" way, because it's handled by the underlying OS
  3. os.path.getsize what should be the same as above

So what is the actual right way to determine the file size? What is the worst way to do it? Or doesn't it even matter, because at the end it is all the same?

(I can imagine the first method having a problem with really large files, while the two others have not.)


Solution

  • The first method would be a waste if you don't need the contents of the file anyway. Either of your other two options are fine. os.path.getsize() uses os.stat()

    From genericpath.py

    def getsize(filename):
        """Return the size of a file, reported by os.stat()."""
        return os.stat(filename).st_size
    

    Edit:

    In case it isn't obvious, os.path.getsize() comes from genericpath.py.

    >>> os.path.getsize.__code__
    <code object getsize at 0x1d457b0, file "/usr/lib/python2.7/genericpath.py", line 47>