Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging multiple files in to a new file [duplicate]

Tags:

python

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?

like image 267
Shraddha Avatar asked Dec 02 '25 05:12

Shraddha


1 Answers

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)
like image 71
Maxime Lorant Avatar answered Dec 03 '25 19:12

Maxime Lorant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!