I think the most Pythonic approach to this particular file problem is to use the fileinput
module (since you either need complex context managers or error handling with open
), I'm going to start with Ashwini's example, but add a few things. The first is that it's better to open with the U
flag for Universal Newlines support (assuming your Python is compiled with it, and most are), (r
is default mode, but explicit is better than implicit). If you're working with other people, it's best to support them giving you files in any format.
import fileinput
for line in fileinput.input(['file1', 'file2'], mode='rU'):
pass
This is also usable on the command line as it will take sys.argv[1:] if you do this:
import fileinput
for line in fileinput.input(mode='rU'):
pass
And you would pass the files in your shell like this:
$ python myscript.py file1 file2