在Python中获取文件大小?

2024-04-24 16:43:15 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有一个内置函数来获取文件对象的字节大小?我看到一些人这样做:

def getSize(fileobject):
    fileobject.seek(0,2) # move the cursor to the end of the file
    size = fileobject.tell()
    return size

file = open('myfile.bin', 'rb')
print getSize(file)

但是根据我对Python的经验,它有很多帮助函数,所以我猜可能有一个内置的。


Tags: 文件theto对象函数sizemove字节
3条回答

您可以使用os.stat()函数,它是系统调用stat()的包装:

import os

def getSize(filename):
    st = os.stat(filename)
    return st.st_size

试着看看http://docs.python.org/library/os.path.html#os.path.getsize

os.path.getsize(path) Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.

import os
os.path.getsize('C:\\Python27\\Lib\\genericpath.py')

或者

os.stat('C:\\Python27\\Lib\\genericpath.py').st_size 
os.path.getsize(path)

返回路径的大小(字节)。如果文件不存在或不可访问,则引发os.error。

相关问题 更多 >