Python concatenate text files

后端 未结 12 2158
無奈伤痛
無奈伤痛 2020-11-22 02:51

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 op

12条回答
  •  天涯浪人
    2020-11-22 03:07

    This should do it

    For large files:

    filenames = ['file1.txt', 'file2.txt', ...]
    with open('path/to/output/file', 'w') as outfile:
        for fname in filenames:
            with open(fname) as infile:
                for line in infile:
                    outfile.write(line)
    

    For small files:

    filenames = ['file1.txt', 'file2.txt', ...]
    with open('path/to/output/file', 'w') as outfile:
        for fname in filenames:
            with open(fname) as infile:
                outfile.write(infile.read())
    

    … and another interesting one that I thought of:

    filenames = ['file1.txt', 'file2.txt', ...]
    with open('path/to/output/file', 'w') as outfile:
        for line in itertools.chain.from_iterable(itertools.imap(open, filnames)):
            outfile.write(line)
    

    Sadly, this last method leaves a few open file descriptors, which the GC should take care of anyway. I just thought it was interesting

提交回复
热议问题