temp.readline()为空?

fpe*_*a06 7 python

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

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
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 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
Run Code Online (Sandbox Code Playgroud)

否则,调用时文件指针位于文件末尾temp.readline().

  • @ fpena06:`NamedTemporaryFile()`返回"类文件对象".文件对象的文档在这里:http://docs.python.org/library/stdtypes.html#file-objects (6认同)