ebroker
ebroker

Reputation: 37

Looking for Simple Python Formula to Combine Two Text Files

Beginner Python user here. I'm trying to write a formula that will merge two text files. As in, the first file should have the text of the second simply added to it, not replacing anything in either file.

Here's what I have so far:

def merge(file1,file2):
    infile = open(file2,'r')
    infile.readline()
    with open('file1','a') as myfile:
        myfile.write('infile')
        myfile.close()

Any help would be greatly appreciated.

Upvotes: 1

Views: 81

Answers (1)

Basil Zuberi
Basil Zuberi

Reputation: 93

You seem to have the right idea, a way it could be simplified and easier to read would be the following code I found on google, fit to your method.

def merge(file1,file2):
    fin = open(file2, "r")
    data2 = fin.read()
    fin.close()
    fout = open(file1, "a")
    fout.write(data2)
    fout.close()

Upvotes: 3

Related Questions