私信  •  关注

nejdetckenobi

nejdetckenobi 最近创建的主题
nejdetckenobi 最近回复了
6 年前
回复了 nejdetckenobi 创建的主题 » python tempfile读写

你错了,因为光标的位置。 当您写入文件时,光标将停在文本的最末端。然后你在读什么都没有。因为游标读取的数据在其位置之后。对于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