I have a list of 20 file names, like ['file1.txt', 'file2.txt', ...]
. I want to write a Python script to concatenate these files into a new file. I could open each file by f = open(...)
, read line by line by calling f.readline()
, and write each line into that new file. It doesn’t seem very “elegant” to me, especially the part where I have to read/write line by line.
Is there a more “elegant” way to do this in Python?
Advertisement
Answer
This should do it
For large files:
JavaScript
x
7
1
filenames = ['file1.txt', 'file2.txt', ]
2
with open('path/to/output/file', 'w') as outfile:
3
for fname in filenames:
4
with open(fname) as infile:
5
for line in infile:
6
outfile.write(line)
7
For small files:
JavaScript
1
6
1
filenames = ['file1.txt', 'file2.txt', ]
2
with open('path/to/output/file', 'w') as outfile:
3
for fname in filenames:
4
with open(fname) as infile:
5
outfile.write(infile.read())
6
… and another interesting one that I thought of:
JavaScript
1
5
1
filenames = ['file1.txt', 'file2.txt', ]
2
with open('path/to/output/file', 'w') as outfile:
3
for line in itertools.chain.from_iterable(itertools.imap(open, filnames)):
4
outfile.write(line)
5
Sadly, this last method leaves a few open file descriptors, which the GC should take care of anyway. I just thought it was interesting