Python Forum
Python csv compare two file, update value if two value is matched
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python csv compare two file, update value if two value is matched
#2
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])
        
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Python csv compare two file, update value if two value is matched - by DeaD_EyE - Apr-17-2019, 10:36 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare current date on calendar with date format file name Fioravanti 1 457 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  How to read csv file update matplotlib column chart regularly SamLiu 2 1,192 Jan-21-2023, 11:33 PM
Last Post: SamLiu
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,279 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Compare variable with values in a file paulo79 1 1,217 Apr-22-2022, 03:16 AM
Last Post: Pedroski55
  Is it possible to update a CSS file from Python bigAL_python 4 2,481 Apr-20-2022, 01:38 PM
Last Post: bigAL_python
  failing to print not matched lines from second file tester_V 14 6,499 Apr-05-2022, 11:56 AM
Last Post: codinglearner
  value null when update in json file 3lnyn0 6 3,789 Dec-30-2021, 05:52 PM
Last Post: ndc85430
  |SOLVED] Glob JPGs, read EXIF, update file timestamp? Winfried 5 2,694 Oct-21-2021, 03:29 AM
Last Post: buran
  Compare two Excel sheets with Python and list diffenrences dmkfon 1 14,990 Oct-09-2021, 03:30 PM
Last Post: Larz60+
Question Python + Google Sheet | Best way to update specific cells in a single Update()? Vokofe 1 2,840 Dec-16-2020, 05:26 AM
Last Post: Vokofe

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020