简体   繁体   English

temp.readline()为空?

[英]temp.readline() empty?

I'm able to create and write to a temp file, however when reading the file lines are empty. 我能够创建和写入临时文件,但是当读取文件行时为空。 I confirmed temp file has content. 我确认临时文件有内容。 Here is my code. 这是我的代码。 Thanks 谢谢

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

You have to re-open (or rewind) the temp file before you can read from it: 您必须重新打开(或倒回)临时文件才能从中读取:

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

Otherwise, the file pointer is positioned at the end of the file when you call temp.readline() . 否则,当您调用temp.readline()时,文件指针位于文件的末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM