【问题标题】:python tempfile read and writepython临时文件读写
【发布时间】:2019-02-01 12:13:40
【问题描述】:

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

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-3.x file temporary-files


    【解决方案1】:

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

    tmp.seek(0)
    

    write 之后,您将继续阅读您在下一个read/readlines 中写的内容。

    如果目标仅仅是使数据对按名称打开文件的其他人可见,例如像nano 这样的外部程序在您注释掉的代码中,您可以跳过seek,但您确实需要确保数据从缓冲区刷新到磁盘,所以在write 之后的同一点,您'加:

    tmp.flush()
    

    【讨论】:

    • 谢谢!成功了
    【解决方案2】:

    由于光标的位置,您错了。 当您写入文件时,光标将停在文本的最后。然后你正在阅读这意味着什么。因为光标读取数据是在它的位置之后。对于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

    【讨论】:

      猜你喜欢
      • 2013-03-10
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      相关资源
      最近更新 更多