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

前端 未结 8 2281
迷失自我
迷失自我 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:32

    Simplest way, is to use itertools.chain,

    which provide an easy way to read from multiple iterators.

    Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

    Let's assume you have to files: file1.txt and file2.txt.

    file1.txt data is:

    file1 line1
    file1 line2
    

    and, the same way, file2.txt data is:

    file2 line1
    file2 line2
    

    This code:

     for f in chain(map(open, ['file1.txt', 'file2.txt'])):
         for line in f:
             print(line.strip())
    

    will output this:

    file1 line1
    file1 line2
    file2 line1
    file2 line2
    

提交回复
热议问题