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

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. Dont forget to close the file after you are done with it ;)


As other answers suggested, you should use seek().

I'll just write an example:

>>> a = open('file.txt')>>> a.read()#output>>> a.seek(0)>>> a.read()#same output


Everyone who has answered this question so far is absolutely right - read() moves through the file, so after you've called it, you can't call it again.

What I'll add is that in your particular case, you don't need to seek back to the start or reopen the file, you can just store the text that you've read in a local variable, and use it twice, or as many times as you like, in your program:

f = f.open()text = f.read() # read the file into a local variable# get the yearmatch = re.search(r'Popularity in (\d+)', text)if match:  print match.group(1)# get all the namesmatches = re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>', text)if matches:  # matches will now not always be None