如何在 Python 中检查文件大小? [英] How can I check file size in Python?
本文介绍了如何在 Python 中检查文件大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在 Windows 中编写 Python 脚本.我想根据文件大小做一些事情.例如,如果大小大于0,我将发送电子邮件给某人,否则继续其他事情.
如何查看文件大小?
解决方案
您需要 st_size
对象的属性由 os.stat
返回.您可以使用 pathlib
(Python 3.4+):
或使用 os.stat
:
输出以字节为单位.
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?
解决方案
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.
这篇关于如何在 Python 中检查文件大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文