Is file object in python an iterable

后端 未结 5 2297
夕颜
夕颜 2020-12-14 09:40

I have a file \"test.txt\":

this is 1st line
this is 2nd line
this is 3rd line

the following code

lines = open(\"test.txt\"         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 10:18

    Yes, file objects are iterators.

    Like all iterators, you can only loop over them once, after which the iterator is exhausted. Your file read pointer is at the end of the file. Re-open the file, or use .seek(0) to rewind the file pointer if you need to loop again.

    Alternatively, try to avoid looping over a file twice; extract what you need into another datastructure (list, dictionary, set, heap, etc.) during the first loop.

提交回复
热议问题