即使在写入数据后,Python NamedTemporaryFile也会显示为空

4sup72z8  于 2023-02-21  发布在  Python
关注(0)|答案(2)|浏览(62)

在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()
k4emjkb1

k4emjkb11#

问题在于刷新。出于效率原因,文件输出被缓冲,因此您必须对它执行flush操作,以便将更改实际写入文件。此外,您应该将其 Package 到with上下文管理器中,而不是显式的.close()

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

0dxa2lsx2#

问题出在查找上。与文件相关的指针指向文件的末尾(因此下一次写操作将在前一次写操作之后继续,但这也意味着读操作返回空字符串)。查找位置0修复了这个问题。

with tempfile.NamedTemporaryFile('w+b') as target_f:
    target_f.write(b"abcde")
    target_f.seek(0)
    assert target_f.read() == b"abcde"

对我有效,冲洗没有任何作用。

相关问题