How to Read File Line by Line Python
Updated by Benjo
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)
NoteThe file object
fileinput.inputabove 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
import fileinput filenames = ['filename_1.txt', 'filename_2.txt', 'filename_3.txt'] # List of lines lines = list(fileinput.input(filenames))
filename = 'filename.txt' # List of lines lines = list(open(filename))
filename = 'filename.txt' with open(filename) as f: # List of lines lines = f.readlines()