Fab*_*bio 2 python file filesize python-2.7
我正在编写一个需要根据文件大小(以字节为单位)对文件执行操作的函数。我想尽量减少传递给函数的参数数量,所以我只会将句柄传递给已经打开的文件,并让函数获取大小。有没有一种优雅的方法来做到这一点?
我正在尝试以下操作,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
Run Code Online (Sandbox Code Playgroud)
然后,从“主代码”
file_id = open(filepath, "rb")
stuff = datafile_profiler(file_id)
file_id.close()
Run Code Online (Sandbox Code Playgroud)
欢迎任何建议(也是一种完全不同的方法)。谢谢。
你可以做一些非常类似的事情:
filesize = os.path.getsize(file_id.name)
Run Code Online (Sandbox Code Playgroud)
这仅适用于file使用open()或类似函数创建的对象,并存储本地文件名。如果您在某个时刻更改目录,或者另一个进程用其他内容替换该文件,则文件名将不再指向与file对象相同的文件。
避免上述问题的另一种获取文件对象大小的方法是:
os.fstat(file_id.fileno()).st_size
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
937 次 |
| 最近记录: |