【发布时间】: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