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: #  w  ww  .j a  v a  2 s. c om
    line = file.readline()      # Read line by line 
    if not line: break 
    print(line.rstrip())        # Line already has a \n

Result

Related Example