Temp.readline () is empty?

I can create and write in a temporary file, however when reading the lines the lines are empty. I confirmed that the 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 
+6
source share
1 answer

You must reopen (or rewind) the temporary file before you can read 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 placed at the end of the file when you call temp.readline() .

+15
source

Source: https://habr.com/ru/post/915064/


All Articles