That's exactly what fileinput is for:
import fileinput
with open(outfilename, 'w') as fout, fileinput.input(filenames) as fin:
for line in fin:
fout.write(line)
For this use case, it's really not much simpler than just iterating over the files manually, but in other cases, having a single iterator that iterates over all of the files as if they were a single file is very handy. (Also, the fact that fileinput
closes each file as soon as it's done means there's no need to with
or close
each one, but that's just a one-line savings, not that big of a deal.)
There are some other nifty features in fileinput
, like the ability to do in-place modifications of files just by filtering each line.
As noted in the comments, and discussed in another post, fileinput
for Python 2.7 will not work as indicated. Here slight modification to make the code Python 2.7 compliant
with open('outfilename', 'w') as fout:
fin = fileinput.input(filenames)
for line in fin:
fout.write(line)
fin.close()
cat file1.txt file2.txt file3.txt ... > output.txt
. In python, if you don't likereadline()
, there is alwaysreadlines()
or simplyread()
. – Grizelcat file1.txt file2.txt file3.txt
command usingsubprocess
module and you're done. But I am not sure ifcat
works in windows. – Ninewith
statement to ensure your files are closed properly, and iterate over the file to get lines, rather than usingf.readline()
. – Elope