Sampath
Sampath

Reputation: 71

How to combine 2 files using python using custom format

with open('file_1.txt', 'r') as file :
    filedata_s = file.read()
with open('file_2.txt', 'r') as file :
    filedata_d = file.read()
print (filedata_s+filedata_d)

file 1 contains name\age\occupation... etc file 2 contains Bob\16\student... Desired output is

Name :- ‘Bob’
Age  :- '16'
Occ  :-'student'
              

Upvotes: 0

Views: 85

Answers (3)

Timus
Timus

Reputation: 11361

Assumption: Input files look like

name/age/occupation
Bob/16/student

If you don't care about padding in the output, you could try:

with open('file_1.txt', 'r') as file1, open('file_2.txt', 'r') as file2:
    for line1, line2 in zip(
        file1.read().rstrip().split("/"), file2.read().rstrip().split("/")
    ):
        print(f"{line1} :- '{line2}'")

The output would look like:

name :- 'Bob'
age :- '16'
occupation :- 'student'

If you want to write it into a new file:

with open('file_1.txt', 'r') as fin1, open('file_2.txt', 'r') as fin2,\
     open('file_3.txt', 'w') as fout:
    fout.writelines(
        f"{line1} :- '{line2}'\n"
        for line1, line2 in zip(
            fin1.read().rstrip().split("/"), fin2.read().rstrip().split("/")
        )
    )

If you care about the padding, you could try:

lines = []
for filename in ('file_1.txt', 'file_2.txt'):
    with open(filename, 'r') as file:
        lines.append(file.read().rstrip().split("/"))
padding = max(map(len, lines[0]))
for line1, line2 in zip(*lines):
    print(f"{line1.ljust(padding)} :- '{line2}'")

The output would look like:

name       :- 'Bob'
age        :- '16'
occupation :- 'student'

Here you have to evaluate the first file fist and use padding = max(map(len, lines[0])) to determine the maximal string length, and then use it with str.ljust() to adjust the output accordingly.

Writing into a new file:

...
with open('file_3.txt', 'w') as file:
    file.writelines(
        f"{line1.ljust(padding)} :- '{line2}'\n" for line1, line2 in zip(*lines)
    )

If you have multiple input lines, I'd use the csv module from the standard library, like

import csv

with open("file_1.txt", "r") as fin1, open("file_2.txt", "r") as fin2:
    reader1 = csv.reader(fin1, delimiter="/")
    reader2 = csv.reader(fin2, delimiter="/")
    for row1, row2 in zip(reader1, reader2):
        for item1, item2 in zip(row1, row2):
            print(f"{item1} :- '{item2}'")

or with padding

with open("file_1.txt", "r") as file:
    padding = max(
        len(item) for row in csv.reader(file, delimiter="/") for item in row
    )

with open("file_1.txt", "r") as fin1, open("file_2.txt", "r") as fin2:
    reader1 = csv.reader(fin1, delimiter="/")
    reader2 = csv.reader(fin2, delimiter="/")
    for row1, row2 in zip(reader1, reader2):
        for item1, item2 in zip(row1, row2):
            print(f"{item1.ljust(padding)} :- '{item2}'")

Upvotes: 1

Vasily
Vasily

Reputation: 44

def read_list(filename):
    result = []
    with open(filename, 'r') as file:
        lines = file.readlines()
        for line in lines:
            result.append(line.strip())
    return result


list_s = read_list('file_1.txt')
list_d = read_list('file_2.txt')

for item in zip(list_s, list_d):
    print(item)

Upvotes: 1

SpawnHeaven Discord
SpawnHeaven Discord

Reputation: 11

with open('file_3.txt', 'w') as file_3:
    with open('file_1.txt', 'r') as file_1:
        with open('file_2.txt', 'r') as file_2:
            for line1, line2 in zip(file_1, file_2):
                print(line1.strip(), line2.strip(), file=file_3)

Upvotes: 1

Related Questions