import csv import argparse def compareAndAdd(base_file, field_base, compare_file, field_compare, field_to_add, output_csv): # Read the base CSV file into a list of dictionaries with open(base_file, 'r', newline='', encoding='utf-8') as csv_file_base: csv_base = list(csv.DictReader(csv_file_base)) # Read the compare CSV file into a list of dictionaries with open(compare_file, 'r', newline='', encoding='utf-8') as csv_file_compare: csv_compare = list(csv.DictReader(csv_file_compare)) # Create a mapping of field_compare to the field_to_add from the compare CSV compare_mapping = {row[field_compare]: row[field_to_add] for row in csv_compare} # Define the output file's fieldnames fieldnames = list(csv_base[0].keys()) + [field_to_add] # Open the output CSV file to write the combined data with open(output_csv, 'w', newline='', encoding='utf-8') as new_file: csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames, delimiter=',') csv_writer.writeheader() # Iterate through the base CSV and add the field_to_add from the compare CSV if field_base matches field_compare for line_base in csv_base: key = line_base[field_base] if key in compare_mapping: line_base[field_to_add] = compare_mapping[key] else: line_base[field_to_add] = None # or some default value if no match is found csv_writer.writerow(line_base) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Compare and add fields from one file to another.') parser.add_argument('base_file', help='The path to the base file') parser.add_argument('field_base', help='The field name in the base file to compare') parser.add_argument('compare_file', help='The path to the compare file') parser.add_argument('field_compare', help='The field name in the compare file to compare') parser.add_argument('field_to_add', help='The field name in the compare file to add to the base file') parser.add_argument('output_file', help='The path to the output file') args = parser.parse_args() compareAndAdd( args.base_file, args.field_base, args.compare_file, args.field_compare, args.field_to_add, args.output_file )