7

我能够创建和写入临时文件,但是在读取文件时行是空的。我确认临时文件有内容。这是我的代码。谢谢

import tempfile
temp = tempfile.NamedTemporaryFile()

with open("~/somefile.txt") as inf:
    for line in inf:
        if line==line.lstrip():
            temp.write(line)

line = str(temp.readline()).strip()
print line #nothing
4

1 回答 1

16

您必须重新打开(或倒带)临时文件,然后才能从中读取:

import tempfile
temp = tempfile.NamedTemporaryFile()

with open("~/somefile.txt") as inf:
    for line in inf:
        if line==line.lstrip():
            temp.write(line)

temp.seek(0) # <=============== ADDED

line = str(temp.readline()).strip()
print line

否则,当您调用temp.readline().

于 2012-05-07T07:26:37.257 回答