[SOLVED] combine multiple text files into one text file?

Issue

This Content is from Stack Overflow. Question asked by u.b

What is the simplest way to combine multiple txt files into one merged file, where each file contains different number of columns and I need to get one merged file with all the columns as follows:

file1.txt
1.04
2.26
3.87

file2.txt
5.44 4.65 9.86
8.67 5.89 7.45
8.41 6.54 6.21

file3.txt
6.98 6.52
4.45 8.74
0.58 4.12

merged.txt
1.04 5.44 4.65 9.86 6.98 6.52
2.26 8.67 5.89 7.45 4.45 8.74
3.87 8.41 6.54 6.21 0.58 4.12

I saw here answer to the case of one columns in each file.

how can i do this for multiple columns?


Solution

here’s a quick-and-dirty solution. I assumed that all files have the exact number of rows. The function write_files gets an input files which is a list of file-paths (strings).

def write_files(files):
    opened_files = []
    for f in files:
        opened_files.append(open(f, "r"))

    output_file = open("output.txt", "w")
    num_lines = sum(1 for line in opened_files[0])
    opened_files[0].seek(0,0)
    for i in range(num_lines):
        line = [of.readline().rstrip() for of in opened_files]
        line = " ".join(line)
        line += "\n"
        output_file.write(line)
    for of in opened_files:
        of.close()
    output_file.close()

write_files(["1.txt", "2.txt"])

This Question was asked in StackOverflow by Cashoo and Answered by noamgot It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?

Exit mobile version