1

我有一个测试设置方法,可以在其中创建一个 tempfile.NamedTemporaryFile。然后我要测试的代码需要读取该文件的内容。当它这样做时,它看起来文件是空的。

import tempfile

fp1 = tempfile.NamedTemporaryFile()
fp1.write('foo')
fp2 = open(fp1.name)
print fp2.read()  # I expect "foo" here
4

1 回答 1

1

发生这种情况的原因是 write 方法是“缓冲的”,换句话说,并非所有对文件系统的 write() 调用都会立即导致磁盘更改。有很多方法可以解决这个问题:

写入()之后的刷新()

import tempfile

fp1 = tempfile.NamedTemporaryFile()
fp1.write('foo')
fp2 = open(fp1.name)
# Because of buffering we've not yet written to the file.
assert fp2.read() == ''
fp1.flush()
# We've now explicitly written to the file.
assert fp2.read() == 'foo'
fp1.close()
fp2.close()

或者您可以将缓冲设置为 0,这是一种丑陋的说法,即“不要缓冲,而是立即写入磁盘”。

# Let's do it again, but now use buffering.
fp1 = tempfile.NamedTemporaryFile(bufsize=0)
fp1.write('foo')
fp2 = open(fp1.name)
# Because we've set buffering to 0 (so no buffering) we've written to the
# file.
assert fp2.read() == 'foo'
fp1.close()
fp2.close()
于 2013-11-12T15:09:53.020 回答