如何在 Python 中检查文件大小?
- 2024-12-17 08:31:00
- admin 原创
- 144
问题描述:
如何在 Python 中获取文件的大小?
解决方案 1:
使用os.path.getsize
:
>>> import os
>>> os.path.getsize("/path/to/file.mp3")
2071611
输出以字节为单位。
解决方案 2:
您需要返回的对象st_size
的属性。您可以使用以下任一方式获取它(Python 3.4+):os.stat
`pathlib`
>>> 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
或使用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
输出以字节为单位。
解决方案 3:
其他答案适用于真实文件,但如果您需要适用于“类文件对象”的东西,请尝试以下操作:
# f is a file-like object.
f.seek(0, os.SEEK_END)
size = f.tell()
在我有限的测试中,它适用于真实文件和 StringIO。(Python 2.7.3。)当然,“类文件对象” API 并不是一个真正的严格接口,但API 文档表明类文件对象应该支持seek()
和tell()
。
编辑
两者之间的另一个区别是,即使您没有读取文件的权限,os.stat()
您也可以读取该文件。显然,除非您有读取权限,否则 seek/tell 方法将不起作用。stat()
编辑2
根据 Jonathon 的建议,这里有一个偏执版本。(上面的版本将文件指针留在文件末尾,因此如果您尝试从文件中读取,您将得到零字节!)
# f is a file-like object.
old_file_position = f.tell()
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(old_file_position, os.SEEK_SET)
解决方案 4:
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:WindowsSystem32mspaint.exe"
print file_size(file_path)
结果:
6.1 MB
解决方案 5:
使用pathlib
(在 Python 3.4 中添加或PyPI上可用的反向移植):
from pathlib import Path
file = Path() / 'doc.txt' # or Path('./doc.txt')
size = file.stat().st_size
这实际上只是一个接口os.stat
,但使用pathlib
提供了一种访问其他文件相关操作的简单方法。
解决方案 6:
bitshift
如果我想将其转换为任何其他单位,我会使用一个技巧bytes
。如果您执行右移,10
则基本上会将其移动一个顺序(多个)。
例子:
5GB are 5368709120 bytes
print (5368709120 >> 10) # 5242880 kilobytes (kB)
print (5368709120 >> 20 ) # 5120 megabytes (MB)
print (5368709120 >> 30 ) # 5 gigabytes (GB)
解决方案 7:
我们有两个选择,都包括导入 os 模块
1)
import os
os.stat("/path/to/file").st_size
asos.stat()
函数返回一个对象,其中包含许多标头,包括文件创建时间和上次修改时间等。其中st_size
给出了文件的确切大小。文件路径可以是绝对路径,也可以是相对路径。
2)在此,我们必须提供准确的文件路径,文件路径可以是相对的也可以是绝对的。
import os
os.path.getsize("path of file")
解决方案 8:
严格坚持这个问题,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>
解决方案 9:
您可以使用模块stat()
中的方法os
。您可以以字符串、字节甚至 PathLike 对象的形式为其提供路径。它也可以与文件描述符一起使用。
import os
res = os.stat(filename)
res.st_size # this variable contains the size of the file in bytes
解决方案 10:
这是另一个不言自明的示例。通过此示例,字节将自动转换为 MB、GB 或 TB。
from pathlib import Path
from psutil._common import bytes2human
def get_readable_filesize(text_file: Path):
return bytes2human(text_file.stat().st_size)
if __name__ == '__main__':
current_file = Path(__file__).parent.resolve()
print(get_readable_filesize(current_file / 'file.txt'))
解决方案 11:
#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 ....