Home > Software design >  How to combine 2 files using python using custom format
How to combine 2 files using python using custom format

Time:03-30

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\n ,age\n ,occupation\n etc file 2 contains Bob\n ,16\n .student\n Desired output is

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

CodePudding user response:

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)

CodePudding user response:

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)
  • Related