如何在Python中获取文件的大小?
当前回答
严格地坚持这个问题,Python代码(+伪代码)将是:
import os
file_path = r"<path to your file>"
if os.stat(file_path).st_size > 0:
<send an email to somebody>
else:
<continue to other things>
其他回答
import os
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
def file_size(file_path):
"""
this function will return the file size
"""
if os.path.isfile(file_path):
file_info = os.stat(file_path)
return convert_bytes(file_info.st_size)
# Lets check the file size of MS Paint exe
# or you can use any file path
file_path = r"C:\Windows\System32\mspaint.exe"
print file_size(file_path)
结果:
6.1 MB
严格地坚持这个问题,Python代码(+伪代码)将是:
import os
file_path = r"<path to your file>"
if os.stat(file_path).st_size > 0:
<send an email to somebody>
else:
<continue to other things>
#Get file size , print it , process it...
#Os.stat will provide the file size in (.st_size) property.
#The file size will be shown in bytes.
import os
fsize=os.stat('filepath')
print('size:' + fsize.st_size.__str__())
#check if the file size is less than 10 MB
if fsize.st_size < 10000000:
process it ....
我们有两个选择,都包括导入os模块
1)
import os
os.stat("/path/to/file").st_size
作为os.stat()函数返回一个包含许多头文件的对象,包括文件创建时间和最后修改时间等。其中st_size给出了文件的确切大小。 文件路径可以是绝对路径也可以是相对路径。
2) 在这里,我们必须提供准确的文件路径,文件路径可以是相对路径也可以是绝对路径。
import os
os.path.getsize("path of file")
使用os.path.getsize:
>>> import os
>>> os.path.getsize("/path/to/file.mp3")
2071611
输出以字节为单位。
推荐文章
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何制作好的可复制的熊猫例子
- 2个数字表的余弦相似度
- 如何从熊猫的两列形成元组列
- 如何读一个文本文件到一个列表或数组与Python
- Django可选url参数
- 在matplotlib上为散点图中的每个系列设置不同的颜色
- 如何加载一个tsv文件到熊猫数据框架?
- 从csv文件创建字典?
- 如何在Python中将十六进制字符串转换为字节?
- set()是如何实现的?
- 如何使Python脚本在Linux中像服务或守护进程一样运行
- 返回大列表中每n项的python方式
- 如何使用Python中的DLL文件?
- 我如何量化两幅图像之间的差异?