# 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)
541
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)
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>
110
#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 ....
8 回答
使用
os.path.getsize
:输出以字节为单位 .
使用os.stat,并使用结果对象的
st_size
成员:输出以字节为单位 .
其他答案适用于真实文件,但如果您需要适用于“类文件对象”的内容,请尝试以下操作:
当然,它适用于真实文件和StringIO 's, in my limited testing. (Python 2.7.3.) The 1302098 API isn'这是一个严格的界面,但API documentation建议文件类对象应该支持
seek()
和tell()
.Edit
这和
os.stat()
之间的另一个区别是你可以stat()
一个文件,即使你没有't have permission to read it. Obviously the seek/tell approach won'工作,除非你有阅读权限 .Edit 2
在Jonathon的建议中,这是一个偏执的版本 . (上面的版本将文件指针留在文件的末尾,所以如果你试图从文件中读取,你将得到零字节!)
结果:
使用
pathlib
(added in Python 3.4并在PyPI上可用)...这实际上只是
os.stat
周围的一个接口,但使用pathlib
提供了一种访问其他文件相关操作的简便方法 .如果我想将
bytes
转换为任何其他单位,我会使用bitshift
技巧 . 如果您通过10
进行右移,则基本上将其移动一个订单(多个) .严格坚持这个问题,python代码(伪代码)将是: