Tuesday, March 23, 2010

How to read a file line by line in Python

The preferred way of reading text files in Python has changed several times over the years, so it's hard to google up a current solution. I think this would be the preferred way as of Python version 2.6.x and 3.1.x. Please comment if this is out of date.

import sys

filename = sys.argv[1]

with open(filename, 'r') as f:
    for line in f:
        dosomething(line)

...or even better, use fileinput which takes the files given as command-line arguments, or if missing, the standard input.

import fileinput

for line in fileinput.input():
    process(line)