如何在Python中获取文件的大小?
当前回答
使用os.path.getsize:
>>> import os
>>> os.path.getsize("/path/to/file.mp3")
2071611
输出以字节为单位。
其他回答
其他答案适用于实际文件,但如果你需要一些适用于“类文件对象”的东西,试试这个:
# f is a file-like object.
f.seek(0, os.SEEK_END)
size = f.tell()
在我有限的测试中,它适用于真实的文件和StringIO。(Python 2.7.3。)当然,“类文件对象”API并不是一个严格的接口,但是API文档建议类文件对象应该支持seek()和tell()。
Edit
这和os.stat()之间的另一个区别是,即使你没有读取权限,你也可以stat()一个文件。显然,除非您有读取权限,否则seek/tell方法将不起作用。
编辑2
根据乔纳森的建议,这是一个偏执的版本。(上面的版本将文件指针留在文件的末尾,所以如果你试图从文件中读取,你将得到零字节!)
# 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)
如果我想从字节转换到任何其他单位,我使用位移位技巧。如果右移10,基本上就是按一个数量级(倍数)移动。
例如:5GB为5368709120字节
print (5368709120 >> 10) # 5242880 kilobytes (kB)
print (5368709120 >> 20 ) # 5120 megabytes (MB)
print (5368709120 >> 30 ) # 5 gigabytes (GB)
你可以使用os模块中的stat()方法。您可以为它提供字符串、字节甚至PathLike对象形式的路径。它也适用于文件描述符。
import os
res = os.stat(filename)
res.st_size # this variable contains the size of the file in bytes
我们有两个选择,都包括导入os模块
1)
import os
os.stat("/path/to/file").st_size
作为os.stat()函数返回一个包含许多头文件的对象,包括文件创建时间和最后修改时间等。其中st_size给出了文件的确切大小。 文件路径可以是绝对路径也可以是相对路径。
2) 在这里,我们必须提供准确的文件路径,文件路径可以是相对路径也可以是绝对路径。
import os
os.path.getsize("path of file")
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