简体   繁体   中英

Python2.7 - reading from tempfile

I use python2.7 and i have a question about reading from 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:

f = tempfile.NamedTemporaryFile("w")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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