在Python中获取文件大小? [英] Getting file size in Python?

查看:293
本文介绍了在Python中获取文件大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个内置函数来获取文件对象的大小(以字节为单位)?我看到有些人做了这样的事情:

Is there a built-in function for getting the size of a file object in bytes? I see some people do something like this:

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的经验来看,它有很多帮助函数,所以我猜可能有一个内置的。

But from my experience with Python, it has a lot of helper functions so I'm guessing maybe there is one built-in.

推荐答案

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


os.path.getsize(path)返回路径的大小,
(以字节为单位)。如果
文件不存在或者
无法访问,请提高os.error。

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 

这篇关于在Python中获取文件大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆