Python 2.7: 只从句柄(而不是路径)获取文件的大小

Python 2.7: get the size of a file just from its handle (and not its path)

我正在编写一个需要根据文件大小(以字节为单位)对文件执行操作的函数。我想尽量减少传递给函数的参数数量,所以我只会将句柄传递给已经打开的文件,让函数获取大小。 有没有一种优雅的方法可以做到这一点?

我尝试了以下 os.path.getsize(os.path.abspath(file_id)),但它不起作用:

def datafile_profiler(file_id):
    filesize = os.path.getsize(os.path.abspath(file_id))

    #[...] continue doing things with the file, based on the size in bites

    return stuff

然后,从 "main code"

file_id = open(filepath, "rb")
stuff = datafile_profiler(file_id)
file_id.close()

欢迎任何建议(也是完全不同的方法)。 塔克斯

你可以像这样做一些非常相似的事情:

filesize = os.path.getsize(file_id.name)

这仅适用于使用 open() 或类似函数创建的 file 对象,并且存储本地文件名。如果您在某个时候更改了目录,或者另一个进程将文件替换为其他文件,文件名将不再指向与 file 对象相同的文件。

另一种避免上述问题的获取文件对象大小的方法是:

os.fstat(file_id.fileno()).st_size

file 个对象有一个 name 属性,所以你可以这样写:

filesize = os.path.getsize(file_id.name)

恕我直言,在不使用名称的情况下做您想做的最直接的方法是使用搜索和讲述。举个例子吧。

def get_file_size(fd):
 fd.seek(0,2)
 return fd.tell()

fd是文件描述符。它可能是使用 open 甚至 StringIO 获得的 id。它会以任何方式工作。