打开文件对象的大小 [英] Size of an open file object

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

问题描述

是否可以找到当前打开的文件对象的大小?

Is there a way to find the size of a file object that is currently open?

具体来说,我正在与tarfile模块一起创建tarfile,但是我不希望我的tarfile超过一定大小.据我所知,tarfile对象是类似文件的对象,因此我想一个通用的解决方案会起作用.

Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.

推荐答案

$ ls -la chardet-1.0.1.tgz
-rwxr-xr-x 1 vinko vinko 179218 2008-10-20 17:49 chardet-1.0.1.tgz
$ python
Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('chardet-1.0.1.tgz','rb')
>>> f.seek(0,2)
>>> f.tell()
179218L

在示例中添加ChrisJY的想法

Adding ChrisJY's idea to the example

>>> import os
>>> os.fstat(f.fileno()).st_size
179218L
>>>        

注意:根据注释,在调用f.tell()之前必须f.seek(0, 2),否则将返回大小为0.

Note: Based on the comments, f.seek(0, 2) is must before calling f.tell(), without which it would return a size of 0. The reason is that f.seek(0, 2) moves the file object's position to the end of the file.

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

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