How to read a file line-by-line in python?

Reading files line-by-line is a common operation when working with text files.

Example:


  with open('file.txt', 'r') as file:
      for line in file:
          print(line)
  

Solution:

Using the with statement ensures that the file is properly closed after it's read. Iterating over the file object directly allows you to read the file line by line.

Beginner's Guide to Python