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)
- The Python Standard Library docs for File Objects
- The Python Tutorial on Input and Output
- Thanks to this thread on stack overflow for the link to fileinput.
- Dive Into Python Working with File Objects




R Bloggers
No comments:
Post a Comment