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

后端 未结 7 1570
挽巷
挽巷 2020-11-21 05:05

For an exercise I\'m doing, I\'m trying to read the contents of a given file twice using the read() method. Strangely, when I call it the second time, it doesn\

7条回答
  •  一生所求
    2020-11-21 05:33

    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 year
    match = re.search(r'Popularity in (\d+)', text)
    if match:
      print match.group(1)
    # get all the names
    matches = re.findall(r'(\d+)(\w+)(\w+)', text)
    if matches:
      # matches will now not always be None
    

提交回复
热议问题