Skip to content Skip to sidebar Skip to footer

Reading Files In Python With For Loop

To read a file in Python, the file must be first opened, and then a read() function is needed. Why is that when we use a for loop to read lines of a file, no read() function is ne

Solution 1:

This is because the file_object class has an "iter" method built in that states how the file will interact with an iterative statement, like a for loop.

In other words, when you say for line in file_object the file object is referencing its __iter__ method, and returning a list where each index contains a line of the file.

Solution 2:

Python file objects define special behavior when you iterate over them, in this case with the for loop. Every time you hit the top of the loop it implicitly calls readline(). That's all there is to it.

Note that the code you are "used to" will actually iterate character by character, not line by line! That's because you will be iterating over a string (the result of the read()), and when Python iterates over strings, it goes character by character.

Solution 3:

The open command in your with statement handles the reading implicitly. It creates a generator that yields the file a record at a time (the read is hidden within the generator). For a text file, each line is one record.

Note that the read command in your second example reads the entire file into a string; this consumes more memory than the line-at-a-time example.

Post a Comment for "Reading Files In Python With For Loop"