Is file object in python iterable

I have a test.txt file:

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

following code

 lines = open("test.txt", 'r') for line in lines: print "loop 1:"+line for line in lines: print "loop 2:"+line 

prints only:

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

It does not print loop2 at all.

Two questions:

  • Is the file object returned by the open () function, is it repeatable? why can it be used in a for loop?

  • Why is loop2 not printing at all?

+6
source share
5 answers

It is not only iterative, it is an iterator, so it can only move through the file once. You can reset the file pointer with .seek(0) , as many have suggested, but in most cases you should only rename the file once.

+25
source

Yes, file objects are iterators.

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

As an alternative, try to avoid looping around the file twice; extract what you need into another data structure (list, dictionary, set, heap, etc.) during the first cycle.

+2
source

Yes, file objects are iterable, but return to the beginning of the file you need to use lines.seek(0) , since after the first loop you are at the end of the file.

+2
source

You are already at the end of the file. File objects are iterators. Once you sort through them, you are in the final position. The iteration will not start again from the very beginning. If you want to start working with the first line again, you need to use lines.seek(0) .

+1
source

It would be better, however, to rewrite the code so that the file does not need to be repeated twice. Read all the lines in some list or do all the processing in one loop.

0
source

Source: https://habr.com/ru/post/946825/


All Articles