Home > Back-end >  concatenate two txt files
concatenate two txt files

Time:02-23

I'm beginner in python, I have two space delimited text files, the first looks like:

a b c
d e f 

the second looks like:

1 2 3
4 5 6

I want to concatenate them vertically such that the output is:

a b c 
d e f
1 2 3
4 5 6

how can I do that using python? and if I want to concatenate horizontally so it looks like this:

a b c 1 2 3
d e f 4 5 6

how can I do it also?

CodePudding user response:

Maybe something like that, using join():

with open("File1", 'r') as f:
    file1 = f.read().split("\n")
with open("File2", 'r') as f:
    file2 = f.read().split("\n")

vertically = "\n".join(file1   file2)
print(vertically)

horizontally = "\n".join([" ".join(line) for line in zip(file1, file2)])
print(horizontally)

CodePudding user response:

For the first output something like this should work.

fin = open("File2.txt", "r")
data2 = fin.read()
fin.close()

fout = open("File1.txt", "a")
fout.write(data2)
fout.close()

For the 2nd one you can try this

file1 = open('myfile.txt', 'r')
Lines = file1.readlines()

for both files, and then combine index 1 in both, and index 2 in both, and make the final merged list and write it to a file.

  • Related