Home > OS >  Python help needed: how do I produce output from 2 txt files
Python help needed: how do I produce output from 2 txt files

Time:11-13

I have 2 simple .txt files. One file contains a person's name and pay. The second file contains a person's name and job title.

Data from first file...

John Doe $750.00

Jane Doe $450.00

Sammy Joe $350.00

Data from second file...

John Doe (Store Manager)

Jane Doe (Asst Store Mngr)

Sammy Joe (Shift Manager)

I need to produce an output like: Persons Name (Job Title) ---- Pay

Example/ John Doe (Store Manager) ---- $450.00

CodePudding user response:

filename = str(input("File Name : ")

file = open(f"{filename}.txt", "w")

filewrite = str(input("Write Content : ")

file.write(filewrite)

sorry but i dont know int print its just str

CodePudding user response:

We could use the pd.merge function here I think

import pandas as pd
file_name_pay = pd.read_fwf('file1.txt')
file_name_jobtitle = pd.read_fwf('file2.txt')
df = pd.merge(file_name_pay,file_name_jobtitle, on = ['name'], how = 'inner')

I would validate if the names were written the same way in both files

CodePudding user response:

You can loop over both files at the same time and separate out the name, job and pay

def my_zip(file_1, file_2):
    for line_1, line_2 in zip(file_1, file_2):
        *name, job = line_1.split()
        pay = line_2.split()[-1]
        yield ' '.join(name), job, pay

with open('file1.txt', 'r') as name_and_job, open('file2.txt','r') as name_and_pay:
    for name, job, pay in my_zip(name_and_job, name_and_pay):
        print(f'{name} {job} --- {pay}')    
  • Related