Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

concatenate two txt files

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)

To save:

with open("File3.txt", 'w') as f:
    f.write(vertically)

with open("File4.txt", 'w') as f:
    f.write(horizontally)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading