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:
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()
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.