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)