Python - Read text file line by line

Introduction

To read by lines or blocks instead, you can use while loop code like this:

Demo

file = open('main.py') 
while True: # www. jav a2  s .  co m
    line = file.readline()      # Read line by line 
    if not line: break 
    print(line.rstrip())        # Line already has a \n

Result

Related Example