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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With