简体   繁体   English

Python2.7-从tempfile读取

[英]Python2.7 - reading from tempfile

I use python2.7 and i have a question about reading from tempfile. 我使用python2.7,我对从tempfile读取有疑问。 Here is my code: 这是我的代码:

import tempfile


for i in range(0,10):
    f = tempfile.NamedTemporaryFile()

    f.write("Hello")

    ##f.seek(0)

    print f.read()

With this code , i get something like this: 有了这段代码,我得到这样的东西:

Rワ
nize.pyR
゙`Sc
d
Rワ
Rワ
Z
Z
nize.pyR
゙`Sc

what are these? 这些是什么?

Thanks! 谢谢!

You are writing string to a file opened in bytes mode. 您正在将字符串写入以字节模式打开的文件。 Add the mode parameter to your call to NamedTemporaryFile: 将mode参数添加到对NamedTemporaryFile的调用中:

f = tempfile.NamedTemporaryFile("w")

See https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files 参见https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM