简体   繁体   中英

python tempfile read and write

I am having issues reading and writing to a tempfile:

import tempfile

def edit(base):
    tmp = tempfile.NamedTemporaryFile(mode='w+')
    #fname = tmp.name
    tmp.write(base)
    #system('nano %s' % fname)
    content = tmp.readlines()
    tmp.close()
    return content

answer = "hi"
print(edit(answer))

Output is [] instead of ["hi"] I don't get the reason behind it,

Help is appreciated

Temporary files are still files; they have a "pointer" to the current position in the file. For a freshly written file, the pointer is at the end of the last write, so if you write without seek ing, you read from the end of the file, and get nothing. Just add:

tmp.seek(0)

after the write and you'll pick up what you wrote in the next read / readlines .

If the goal is solely to make the data visible to something else opening the file by name, eg an outside program like nano in your commented out code, you can skip the seek , but you do need to make sure the data is flushed from buffer to disk, so at the same point after the write , you'd add:

tmp.flush()

You're wrong because of the cursor's position. When you write to a file, cursor will stop at the very end of your text. Then you're reading which means nothing. Because cursor reads the data comes after its position. For quickfix, the code must be like this:

import tempfile

def edit(base):
    tmp = tempfile.NamedTemporaryFile(mode='w+')
    #fname = tmp.name
    tmp.write(base)
    tmp.seek(0, 0)  # This will rewind the cursor
    #system('nano %s' % fname)
    content = tmp.readlines()
    tmp.close()
    return content

answer = "hi"
print(edit(answer))

You may want to read the documentation about that. https://docs.python.org/3/tutorial/inputoutput.html?highlight=seek#methods-of-file-objects

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