How do I determine an open file's size in Python?

Jason Baker picture Jason Baker · Dec 8, 2009 · Viewed 11k times · Source

There's a file that I would like to make sure does not grow larger than 2 GB (as it must run on a system that uses ext 2). What's a good way to check a file's size bearing in mind that I will be writing to this file in between checks? In particular, do I need to worry about buffered, unflushed changes that haven't been written to disk yet?

Answer

Dominic Bou-Samra picture Dominic Bou-Samra · Dec 8, 2009

Perhaps not what you want, but I'll suggest it anyway.

import os
a = os.path.getsize("C:/TestFolder/Input/1.avi")

Alternatively for an opened file you can use the fstat function, which can be used on an opened file. It takes an integer file handle, not a file object, so you have to use the fileno method on the file object:

a = open("C:/TestFolder/Input/1.avi")
b = os.fstat(a.fileno()).st_size