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

后端 未结 7 1551
挽巷
挽巷 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:44

    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 ;)

提交回复
热议问题