Py学习  »  Python

python tempfile读写

protoneight • 5 年前 • 1636 次点击  

我在读写临时文件时遇到问题:

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))

输出为 [] 而不是 ["hi"] 我不明白背后的原因,

感谢您的帮助

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50779
 
1636 次点击  
文章 [ 2 ]  |  最新文章 5 年前
ShadowRanger
Reply   •   1 楼
ShadowRanger    6 年前

临时文件仍然是文件;它们有一个指向文件中当前位置的“指针”。对于新编写的文件,指针位于最后一次写入的末尾,因此如果 write 没有 seek ing,你从文件的末尾读,什么也得不到。只需添加:

tmp.seek(0)

之后 你会在接下来的时间里收到你写的东西 read / readlines .

如果目标仅仅是使数据对其他按名称打开文件的程序可见,例如 nano 在注释掉的代码中,可以跳过 寻求 ,但您确实需要确保数据从缓冲区刷新到磁盘,因此在 ,您将添加:

tmp.flush()
nejdetckenobi
Reply   •   2 楼
nejdetckenobi    6 年前

你错了,因为光标的位置。 当您写入文件时,光标将停在文本的最末端。然后你在读什么都没有。因为游标读取的数据在其位置之后。对于quickfix,代码必须如下:

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))

您可能需要阅读有关该操作的文档。 https://docs.python.org/3/tutorial/inputoutput.html?highlight=seek#methods-of-file-objects