Python concatenate text files

后端 未结 12 1974
無奈伤痛
無奈伤痛 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:25

    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()
    

提交回复
热议问题