merging multiple files in to a new file

python

Solution

The response is already here:

filenames = ['file1.txt', 'file2.txt', ...]
with open('result.txt', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)

Flat line solution

What you need (according to comments), is a file with only 2 lines. On the first line, the content of the first file (without break lines) and on the second line, the second file. So, if your files are small (less than ~1MB each, after it can take a lot of memory...)

filenames = ['file1.txt', 'file2.txt', ...]
with open('result.txt', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            content = infile.read().replace('\n', '')
            outfile.write(content)

Problem

I have 2 text files, like ['file1.txt', 'file2.txt']. I want to write a Python script to concatenate these files into a new file, using basic functions like open() to open each file, read line by line by calling f.readline(), and write each line into that new file using f.write(). I am new to file handling programming in python. Can someone help me with this?

Original source

Related problems