简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM