【问题标题】:Python NamedTemporaryFile appears empty even after data is written即使在写入数据后,Python NamedTemporaryFile 也显示为空
【发布时间】:2017-09-01 16:48:55
【问题描述】:

在 Python 2 中,创建和访问临时文件很容易。然而,在 Python 3 中,情况似乎不再如此。我对如何获取使用 tempfile.NamedTemporaryFile() 创建的文件感到困惑,因此我可以对其调用命令。

例如:

temp = tempfile.NamedTemporaryFile()
temp.write(someData)
subprocess.call(['cat', temp.name]) # Doesn't print anything out as if file was empty (would work in python 2)
subprocess.call(['cat', "%s%s" % (tempfile.gettempdir(), temp.name])) # Doesn't print anything out as if file was empty
temp.close()

【问题讨论】:

  • 适合我吗? temp.name 给了我正确的文件名 ("/var/folders/ck/s38sycld0tvgb5qhmqtf750r0000gn/T/tmp7ejqww3s")
  • “不起作用”是什么意思?这不是一个充分的问题规范。而且,就目前而言,它对我来说效果很好......
  • 好吧,我有一个猜测:在 write 调用之后调用 temp.flush()。您正在写入的数据被缓冲。
  • 感谢 L3viathan!这似乎解决了我的问题
  • 这不是 NamedTemporaryFile 特有的——您也可以使用 temp = file.open('filename', 'w') 获得完全相同的行为。

标签: python python-3.x temporary-files


【解决方案1】:

问题在于冲洗。出于效率原因,文件输出被缓冲,因此您必须 flush 它才能将更改实际写入文件。此外,您应该将其包装到 with 上下文管理器中,而不是显式的 .close()

with tempfile.NamedTemporaryFile() as temp:
    temp.write(someData)
    temp.flush()
    subprocess.call(['cat', temp.name])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多