I am writing a Python script in Windows. I want to do something based on the file size. For example, if the size is greater than 0, I will send an email to somebody, otherwise continue to other things.
How do I check the file size?
I am writing a Python script in Windows. I want to do something based on the file size. For example, if the size is greater than 0, I will send an email to somebody, otherwise continue to other things.
How do I check the file size?
Strictly sticking to the question, the python code (+ pseudo-code) would be:
Result:
The other answers work for real files, but if you need something that works for "file-like objects", try this:
It works for real files and StringIO's, in my limited testing. (Python 2.7.3.) The "file-like object" API isn't really a rigorous interface, of course, but the API documentation suggests that file-like objects should support
seek()
andtell()
.Edit
Another difference between this and
os.stat()
is that you canstat()
a file even if you don't have permission to read it. Obviously the seek/tell approach won't work unless you have read permission.Edit 2
At Jonathon's suggestion, here's a paranoid version. (The version above leaves the file pointer at the end of the file, so if you were to try to read from the file, you'd get zero bytes back!)
Use
os.stat
, and use thest_size
member of the resulting object:Output is in bytes.
Using
os.path.getsize
:The output is in bytes.