Python - 无法读取 tempfile.TemporaryFile;为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1202848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:42:13  来源:igfitidea点击:

Python - tempfile.TemporaryFile cannot be read; why?

pythonfileiotemporary-files

提问by Sridhar Ratnakumar

The official documentation for TemporaryFilereads:

TemporaryFile官方文档如下:

The mode parameter defaults to 'w+b' so that the file created can be read and written without being closed.

mode 参数默认为 'w+b' 以便创建的文件可以在不关闭的情况下进行读写

Yet, the below code does not work as expected:

然而,下面的代码没有按预期工作:

import tempfile

def play_with_fd():
    with tempfile.TemporaryFile() as f:
        f.write('test data\n')
        f.write('most test data\n')

        print 'READ:', f.read()

        f.write('further data')

        print 'READ:', f.read()

        f.write('even more')
        print 'READ:', f.read()

        print 'READ:', f.read()
        print 'READ:', f.read()

if __name__ == '__main__':
    play_with_fd()

The output I get is:

我得到的输出是:

> python play.py 
READ: 
READ: 
READ: 
READ: 
READ: 

Can anyone explain this behavior? Is there a way to read from temporary files at all? (without having to use the low-level mkstemp that wouldn't automatically delete the files; and I don't care about named files)

谁能解释这种行为?有没有办法从临时文件中读取?(不必使用不会自动删除文件的低级 mkstemp;而且我不关心命名文件)

回答by ramosg

You must put

你必须把

f.seek(0)

before trying to read the file (this will send you to the beginning of the file), and

在尝试读取文件之前(这会将您发送到文件的开头),以及

f.seek(0, 2)

to return to the end so you can assure you won't overwrite it.

返回到最后,这样您就可以确保不会覆盖它。

回答by Heikki Toivonen

read()does not return anything because you are at the end of the file. You need to call seek()first before read()will return anything. For example, put this line in front of the first read():

read()不返回任何内容,因为您在文件末尾。您需要先致电,seek()然后read()才能返回任何内容。例如,将此行放在第一个之前read()

f.seek(-10, 1)

Of course, before writing again, be sure to seek()to the end (if that is where you want to continue writing to).

当然,再写之前,一定要写到seek()最后(如果那是你想继续写的地方)。