Using a For Loop to Read Text Files

 

In addition to using the readline() method above to read a text file, we can also use a for loop. In fact, the for loop is a more elegant and efficient way to read text files. The following program shows how this is done.

 

f = open (‘myfile.txt’, 'r')

 

for line in f:

print (line, end = ‘’)

 

f.close()

 

The for loop loops through the text file line by line. When you run it, you’ll get

 

Learn Python in One Day and Learn It Well

Python for Beginners with Hands-on Project

The only book you need to start coding in Python immediately

http://www.learncodingfast.com/python