Concatenate multiple files into a single file object without creating a new file

前端 未结 8 2272
迷失自我
迷失自我 2021-02-12 16:37

This question is related to Python concatenate text files

I have a list of file_names, like [\'file1.txt\', \'file2.txt\', ...].

I wou

8条回答
  •  粉色の甜心
    2021-02-12 17:16

    Let's say multiple_files is a list which contain all file names

    multiple_files = ["file1.txt", "file2.txt", "file3.txt", ...] # and so on...
    

    Open the output file which will contain all

    f = open("multiple_files.txt", "w")
    for _file in multiple_files:
        f.write(_file.read())
    

    This way you don't have to read each and every line of your files.

    Although the above method is simpler, You also have fileinput module as an alternative.

    fileinput docs

    You can use fileinput to access and process multiple files.

    Example:

    with fileinput.input(files=('file1.txt', 'file2.txt')) as f:
        for line in f:
            process(line)
    

提交回复
热议问题