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?
Use os.path.getsize() function Use the os. path. getsize('file_path') function to check the file size. Pass the file name or file path to this function as an argument.
Locate the file or folder whose size you would like to view. Click the file or folder. Press Command + I on your keyboard. A window opens and shows the size of the file or folder.
import os fsize=os. stat('filepath') print('size:' + fsize. st_size.
Using os.path.getsize
:
>>> import os >>> b = os.path.getsize("/path/isa_005.mp3") >>> b 2071611
The output is in bytes.
You need the st_size
property of the object returned by os.stat
. You can get it by either using pathlib
(Python 3.4+):
>>> from pathlib import Path >>> Path('somefile.txt').stat() os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400) >>> Path('somefile.txt').stat().st_size 1564
or using os.stat
:
>>> import os >>> os.stat('somefile.txt') os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400) >>> os.stat('somefile.txt').st_size 1564
Output is in bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With