【问题标题】:How can I get the size of a TemporaryFile in python? [duplicate]如何在 python 中获取 TemporaryFile 的大小? [复制]
【发布时间】:2018-09-30 18:07:38
【问题描述】:

目前当我写一个临时的:

import tempfile
a = tempfile.TemporaryFile()

a.write(...)

# The only way I know to get the size
a.seek(0)
len(a.read())

有没有更好的办法?

【问题讨论】:

  • 不是重复的,另一个问题是关于常规文件而不是没有路径的临时文件。
  • 已经回答的stackoverflow线程没有任何与临时文件相关的解决方案(尤其是SpooledTemporaryFile),这个帖子应该重新打开

标签: python


【解决方案1】:
import tempfile
a = tempfile.TemporaryFile()
a.write('abcd')
a.tell()
# 4

a.tell() 为您提供文件中的当前位置。如果您只是附加,这将是准确的。如果您使用 seek 来跳转文件,则首先使用以下命令搜索到文件末尾: a.seek(0, 2) 第二个参数“whence”=2 表示相对于文件末尾的位置。 https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

【讨论】:

  • 您的意思是a.write('abcd') 吗?
  • @mkamioner - 哎呀 - 确实。
【解决方案2】:

您可以使用os.stat 假设文件已关闭或所有挂起的写入已被刷新

os.stat(a.name).st_size

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 2016-05-31
    • 2013-06-16
    • 2011-08-15
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    相关资源
    最近更新 更多