Why can’t I call read() twice on an open file?

Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines() or iterate through lines with for line in handle:.

To answer your question directly, once a file has been read, with read() you can use seek(0) to return the read cursor to the start of the file (docs are here). If you know the file isn’t going to be too large, you can also save the read() output to a variable, using it in your findall expressions.

Ps. Don’t forget to close the file after you are done with it.

Leave a Comment