Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check file size in Python?

Tags:

python

file

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?

like image 738
5YrsLaterDBA Avatar asked Jan 20 '10 18:01

5YrsLaterDBA


People also ask

How do you check the size of the file using Python?

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.

How do you check a files size?

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.

How does Python compare files in size?

import os fsize=os. stat('filepath') print('size:' + fsize. st_size.


2 Answers

Using os.path.getsize:

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

The output is in bytes.

like image 120
danben Avatar answered Sep 23 '22 10:09

danben


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.

like image 21
Adam Rosenfield Avatar answered Sep 23 '22 10:09

Adam Rosenfield