How to Read File Line by Line Python

Read a file line by line using Python, read file into a list line by line, read text file line by line

If you have a CSV file, you may want to read csv file instead. In case you have a text-based file and want to to read lines from that file using Python, let check following approaches:

1. Iterate over file object

File objects are lazy iterators, so just iterate over it after openning it.

filename = 'filename.txt'
with open(filename) as f:
    for line in f:
        print(line)

Alternatively, if you have multiple files, use fileinput.input, another lazy iterator:

import fileinput

filenames = ['filename_1.txt', 'filename_2.txt', 'filename_3.txt']
for line in fileinput.input(filenames):
    print(line)
Note
The file object f and fileinput.input above both are/return lazy iterators. You can only use an iterator one time.

2. Read text file line by line to list

If you want to get the list of lines, you can cast the iterator into list

import fileinput

filenames = ['filename_1.txt', 'filename_2.txt', 'filename_3.txt']
# List of lines
lines = list(fileinput.input(filenames))

or

filename = 'filename.txt'
# List of lines
lines = list(open(filename))

or using readlines()

filename = 'filename.txt'
with open(filename) as f:
  # List of lines
  lines = f.readlines()
Last modified October 4, 2020