dan*_*ben 1018
使用os.path.getsize:
>>> import os
>>> b = os.path.getsize("/path/isa_005.mp3")
>>> b
2071611L
Run Code Online (Sandbox Code Playgroud)
输出以字节为单位.
Ada*_*eld 644
使用os.stat,并使用st_size结果对象的成员:
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L
Run Code Online (Sandbox Code Playgroud)
输出以字节为单位.
Mar*_*ase 124
其他答案适用于真实文件,但如果您需要适用于"类文件对象"的内容,请尝试以下操作:
# f is a file-like object.
f.seek(0, os.SEEK_END)
size = f.tell()
Run Code Online (Sandbox Code Playgroud)
在我的有限测试中,它适用于真实文件和StringIO.(Python 2.7.3.)当然,"类文件对象"API并不是一个严格的界面,但是API文档建议类文件对象应该支持seek()和tell().
编辑
另一个区别os.stat()是,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)
Run Code Online (Sandbox Code Playgroud)
Raj*_*rma 67
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)
Run Code Online (Sandbox Code Playgroud)
结果:
6.1 MB
Run Code Online (Sandbox Code Playgroud)
pum*_*azi 36
使用pathlib(在Python 3.4中添加并在PyPI上可用)......
from pathlib import Path
file = Path() / 'doc.txt' # or Path('./doc.txt')
size = file.stat().st_size
Run Code Online (Sandbox Code Playgroud)
这实际上只是一个接口os.stat,但使用pathlib提供了一种访问其他文件相关操作的简便方法.
gun*_*uri 19
我们有两个选择都包括导入 os 模块
1)
import os
os.stat("/path/to/file").st_size
Run Code Online (Sandbox Code Playgroud)
asos.stat()函数返回一个对象,其中包含许多标头,包括文件创建时间和上次修改时间等。其中st_size给出了文件的确切大小。文件路径可以是绝对路径或相对路径。
2)在此,我们必须提供准确的文件路径,文件路径可以是相对路径或绝对路径。
import os
os.path.getsize("path of file")
Run Code Online (Sandbox Code Playgroud)
use*_*754 13
bitshift如果我想转换bytes到任何其他单位,我会使用一个技巧.如果你做右移,10你基本上按顺序(多次)移动它.
例:
5GB are 5368709120 bytes
print (5368709120 >> 10) # 5242880 kilo Bytes (kB)
print (5368709120 >> 20 ) # 5120 Mega Bytes(MB)
print (5368709120 >> 30 ) # 5 Giga Bytes(GB)
Run Code Online (Sandbox Code Playgroud)
严格坚持这个问题,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>
Run Code Online (Sandbox Code Playgroud)