Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

temp.readline() empty?

Tags:

python

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
like image 912
fpena06 Avatar asked May 07 '12 07:05

fpena06


1 Answers

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().

like image 146
NPE Avatar answered Sep 23 '22 19:09

NPE