How to check file size in python?


Question

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?

1
652
3/28/2019 8:15:10 PM

Accepted Answer

Use os.stat, and use the st_size member of the resulting object:

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L

Output is in bytes.

611
7/21/2016 1:17:41 PM

Using os.path.getsize:

>>> import os
>>> b = os.path.getsize("/path/isa_005.mp3")
>>> b
2071611L

The output is in bytes.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon