Search code examples
pythonfilepython-2.7filesize

Python 2.7: get the size of a file just from its handle (and not its path)


I am writing a function that needs to do things on a file, based on the file-size (in bytes). I would like to minimize the number of parameters to pass to the function, so I would only pass the handle to the already-open file, and let the function get the size. Is there an elegant way to do this?

I was trying the following, with os.path.getsize(os.path.abspath(file_id)), but it doesn't work:

def datafile_profiler(file_id):
    filesize = os.path.getsize(os.path.abspath(file_id))

    #[...] continue doing things with the file, based on the size in bites

    return stuff

and then, from the "main code"

file_id = open(filepath, "rb")
stuff = datafile_profiler(file_id)
file_id.close()

Any suggestion (also a totally different approach) is welcome. Thaks.


Solution

  • You can do something very similar like this:

    filesize = os.path.getsize(file_id.name)
    

    This will only work on file objects created using open() or similar functions, and that stores a local file name. If you change directories at some point, or another process replaces the file with something else, the file name will no longer point to the same file as the file object.

    Another way to get the size of the file object that avoids the above problems is:

    os.fstat(file_id.fileno()).st_size