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

Viewed 10992

This question is related to Python concatenate text files

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

I would like to open all the files into a single file object that I can read through line by line, but I don't want to create a new file in the process. Is that possible?

with open(file_names, 'r') as file_obj:
   line = file_obj.readline()
   while line:
       ...
8 Answers

Instead of making python read multiple files, pipe the contents from the shell and read it from stdin. This will also make your program more flexible as you can pass in any set of files into your python program without changing your code.

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

Related