Tapasvi Bhatt
Tapasvi Bhatt

Reputation: 35

Printing contents of a file with and without using readlines() method

I have started learning python and came across the following code to print the contents of a file :

with open('Example2.txt','r') as readfile:
     for line in readfile:
          print(line)

The output was as follows :

This is line A

This is line B

This is line C

This is line D

The source if the information says that the for loop takes input line by line and then prints it, but as far as I know (please correct me if I am wrong), the variable readfile contains a single string then how come the loop is running multiple times? It must be printing the contents of the file in a single go.

Also, this is the code that I think is correct to read the file line by line and this prints the same output too. Then what is the difference between the previous code and this code?

with open('Example2.txt','r') as readfile:
     for line in readfile.readlines():
          print(line)

Upvotes: 1

Views: 518

Answers (1)

afterburner
afterburner

Reputation: 2781

Actually, the readfile variable is a file object, which has an __iter__ method, where each index of the __iter__ corresponds to a line in your file. For more information, check this similar question: Reading files in Python with for loop

The actual type definition can be found here and it inherits from BufferedIOBase, which in turn inherits from IOBase, where the readlines method is defined

The difference between the two code snippets is that in the first one, you're relying on the implementation of TextIOWrapper, which is essentially syntactic sugar, to call readlines for you, while in the second one, you're explicitly making the call.

Upvotes: 1

Related Questions