如何在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>

其他回答

使用os.path.getsize:

>>> import os
>>> os.path.getsize("/path/to/file.mp3")
2071611

输出以字节为单位。

如果我想从字节转换到任何其他单位,我使用位移位技巧。如果右移10,基本上就是按一个数量级(倍数)移动。

例如:5GB为5368709120字节

print (5368709120 >> 10)  # 5242880 kilobytes (kB)
print (5368709120 >> 20 ) # 5120 megabytes (MB)
print (5368709120 >> 30 ) # 5 gigabytes (GB)

严格地坚持这个问题,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>

你可以使用os模块中的stat()方法。您可以为它提供字符串、字节甚至PathLike对象形式的路径。它也适用于文件描述符。

import os

res = os.stat(filename)

res.st_size # this variable contains the size of the file in bytes

使用pathlib(在Python 3.4或PyPI上可用的backport中添加):

from pathlib import Path
file = Path() / 'doc.txt'  # or Path('./doc.txt')
size = file.stat().st_size

这实际上只是一个围绕os的界面。但是使用pathlib提供了一种访问其他文件相关操作的简单方法。