Python Forum

Full Version: Python csv compare two file, update value if two value is matched
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
After reviewed few recommend similar topic about comparing value, there is not much help for me.
car.csv
    
    tittle1,tittle2
    bmw,2000
    mercedes,2000
    toyota,1000
    honda,1500
    geely,500

price.csv

    ori_price1,new_price2
    2000,5000
    1000,2500
The result should looks like
tittle1,tittle2

    bmw,5000
    mercedes,5000
    toyota,2500
    honda,1500
    geely,500
I did try the code below

    import csv
    
        with open('car.csv', 'r') as csv_file, open('price.csv', 'r', newline='') as csv_file2 \
                ,open('result.csv', 'w', newline='') as new_file:
            csv_reader = csv.DictReader(csv_file)
            csv_reader2 = csv.DictReader(csv_file2)
            csv_writer = csv.writer(new_file)
        
            csv_writer.writerow([ 'tittle1', 'title2'])
        
            for row1,row2 in zip(csv_reader,csv_reader2):
              csv_writer.writerow([row1['tittle1'],row1['tittle2'],row2['new_price2']])
The code only replaces the whole column without comparing the value.
This should work.
Some magic to remove white spaces from nested rows and using tuple unpacking.
If you can, use pathlib.Path, but it's not mandatory.


from pathlib import Path
import csv


csv_file1 = Path('car.csv')
csv_file2 = Path('price.csv')
new_file = Path('result.csv')


with csv_file1.open() as fd_car, csv_file2.open() as fd_price,\
    new_file.open('w') as fd_result:
    cars = csv.reader(fd_car)
    prices = csv.reader(fd_price)
    writer = csv.writer(fd_result)
    # skipping headers
    next(cars)
    next(prices)
    for rows in zip(cars, prices):
        # strip whitespaces
        (car, car_price), (old_price, new_price) = (map(lambda s: s.strip(), row) for row in rows)
        print('car-row:', car, car_price, 'price-row:', old_price, new_price)
        # compare price with old_price
        # remind, that you compare strings
        if car_price != old_price:
            print('Price missmatch, skipping', car)
            continue
        writer.writerow([car, new_price])