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

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

    Using built-ins:

    product=[]
    for File in ['file1.txt','file2.txt','file3.txt']:
        for line in open(File,'r').readlines():
            product.append(line)
    
    for line in product:print(line)
    

    file.readlines() outputs the contents to a list and the file is closed.

    You could also write:

    product=[]
    for File in ['file1.txt','file2.txt','file3.txt']:
        product+=open(File).readlines()
    

    It's shorter and probably faster but I use the first because it reads better to me.

    Cheers

提交回复
热议问题