Home > Enterprise >  I have two csv files which needs to be compare to each other using for loop
I have two csv files which needs to be compare to each other using for loop

Time:11-04

I'm a newbie trying to do this in python, Is there an easy way of doing this?

I have two CSV files

This is the first CSV file

filename,file_serial_number
file1, 1F
file2, 2E
file3, 3C

This is the second CSV file

filename,file_serial_number
file1, 1A
file2, 2C
file3, 3E

This is my code:

import csv

csv_file1 = r'csv_file.csv'
csv_file2 = r'csv_file(1).csv'

with open(csv_file1, 'r') as file1_csv, open(csv_file2, 'r') as file2_csv:
fileone = csv.DictReader(file1_csv)
filetwo = csv.DictReader(file2_csv)
file1_serial_list = []
for row_f1 in fileone:
    f1_filename = row_f1['filename']
    f1_file_serial = row_f1['file_serial_number']
    file_serial_list.append(f1_file_serial)


file2_serial_list = []
for row_f2 in filetwo:
    f2_filename = f1['filename']
    f2_file_serial = f1['file_serial_number']
    file_serial_list.append(f2_file_serial)

for serial1, serial2 in zip(file1_serial_list, file2_serial_list):
    if serial1 > serial2:
        # This should output the filenames with greater serial on csv_file1.
        print(f1_filename)

# Output should be:
    file1
    file2

CodePudding user response:

You can directly zip the DictReaders.

for row_f1, row_f2 in zip(fileone, filetwo):
    print(row_f1['filename'] 
           if row_f1['file_serial_number'] > row_f2['file_serial_number'] 
                else row_f2['filename'])
  • Related