How to read a text file line by line in Python?

To read a text file line by line in Python, you can use the readline() method or iterate over the file object directly. Here are two examples:

  1. Using readline() method:
with open('file.txt', 'r') as file: line = file.readline() while line: print(line.strip()) # strip() removes any trailing newlines or whitespaces line = file.readline()
  1. Iterating over the file object:
with open('file.txt', 'r') as file: for line in file: print(line.strip())

Both methods read the file line by line until the end of the file is reached. In each iteration, the line variable holds the current line of text, which is then printed or can be further processed as needed.