Compare Two Csv Files Using Python - GeeksforGeeks (2024)

We are given two files and our tasks is to compare two CSV files based on their differences in Python. In this article, we will see some generally used methods for comparing two CSV files and print differences.

Compare Two CSV Files for Differences in Python

Below are some of the ways by which we can compare two CSV files for differences in Python:

file1.csv

Name,Age,CityJohn,25,New YorkEmily,30,Los AngelesMichael,40,Chicago

file2.csv

Name,Age,CityJohn,25,New YorkMichael,45,ChicagoEmma,35,San Francisco

Compare Two CSV Files Using Pandas library

In this approach, the Python Program loads both the CSV files (‘file1.csv’ & ‘file2.csv’) into two DataFrames. Once the CSV files are loaded, the compare() method provided by Pandas allows us to efficiently identify differences between the two DataFrames by comparing each corresponding row between the two DataFrames.

Python3
import pandas as pd# Read CSV filesdf1 = pd.read_csv('file1.csv')df2 = pd.read_csv('file2.csv')# Compare dataframesdiff = df1.compare(df2)# Print the differencesprint("Differences between file1 and file2:")print(diff)

Output

Differences between file1 and file2: Name Age City self other self other self other1 Emily Michael 30.0 45.0 Los Angeles Chicago2 Michael Emma 40.0 35.0 Chicago San Francisco

Compare Two CSV Files Using CSV Module

In this approach, the Python Program reads both the CSV files (‘file1.csv’ & ‘file2.csv’) using csv.reader function in reading mode. Then iterate over the rows of both CSV files and compare them.

Python3
import csv# Function to compare two CSV filesdef compare(file1, file2): differences = [] # Open both CSV files in read mode with open(file1, 'r') as csv_file1, open(file2, 'r') as csv_file2: reader1 = csv.reader(csv_file1) reader2 = csv.reader(csv_file2) # Iterate over rows in both files simultaneously for row1, row2 in zip(reader1, reader2): if row1 != row2: differences.append((row1, row2)) return differences# Define file pathsfile1 = 'file1.csv'file2 = 'file2.csv'# Call the compare_csv_files function and store the differencesdifferences = compare(file1, file2)for diff in differences: print(f"Difference found: {diff}")

Output

Difference found: (['Emily', '30', 'Los Angeles'], ['Michael', '45', 'Chicago'])Difference found: (['Michael', '40', 'Chicago'], ['Emma', '35', 'San Francisco'])


Please Login to comment...

Compare Two Csv Files Using Python - GeeksforGeeks (2024)
Top Articles
BIG List Of Stocking Stuffer Ideas For Preppers, Outdoorsmen, & Campers
Best Canadian Travel Insurance For Extreme Sports
Northern Counties Soccer Association Nj
Duralast Gold Cv Axle
Exclusive: Baby Alien Fan Bus Leaked - Get the Inside Scoop! - Nick Lachey
Palm Coast Permits Online
Cosentyx® 75 mg Injektionslösung in einer Fertigspritze - PatientenInfo-Service
Ogeechee Tech Blackboard
Craigslist Phoenix Cars By Owner Only
Midway Antique Mall Consignor Access
Mikayla Campinos Videos: A Deep Dive Into The Rising Star
Gfs Rivergate
Idaho Harvest Statistics
Chelactiv Max Cream
Arre St Wv Srj
Walgreens Alma School And Dynamite
Vegas7Games.com
Espn Horse Racing Results
Phoebus uses last-second touchdown to stun Salem for Class 4 football title
Silky Jet Water Flosser
Shoe Station Store Locator
CVS Health’s MinuteClinic Introduces New Virtual Care Offering
Cosas Aesthetic Para Decorar Tu Cuarto Para Imprimir
Revelry Room Seattle
Courtney Roberson Rob Dyrdek
Ff14 Sage Stat Priority
Trust/Family Bank Contingency Plan
What are the 7 Types of Communication with Examples
Swgoh Boba Fett Counter
Solarmovie Ma
Craigslist Org Sf
2012 Street Glide Blue Book Value
Prima Healthcare Columbiana Ohio
Tenant Vs. Occupant: Is There Really A Difference Between Them?
Go Smiles Herndon Reviews
Skyrim:Elder Knowledge - The Unofficial Elder Scrolls Pages (UESP)
Academic important dates - University of Victoria
The Best Restaurants in Dublin - The MICHELIN Guide
Temu Y2K
Froedtert Billing Phone Number
Encompass.myisolved
“To be able to” and “to be allowed to” – Ersatzformen von “can” | sofatutor.com
Author's Purpose And Viewpoint In The Dark Game Part 3
The best specialist spirits store | Spirituosengalerie Stuttgart
Craigslist Central Il
Guy Ritchie's The Covenant Showtimes Near Look Cinemas Redlands
Puss In Boots: The Last Wish Showtimes Near Valdosta Cinemas
Helpers Needed At Once Bug Fables
Deviantart Rwby
Factorio Green Circuit Setup
Volstate Portal
Latest Posts
Article information

Author: Kareem Mueller DO

Last Updated:

Views: 6489

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Kareem Mueller DO

Birthday: 1997-01-04

Address: Apt. 156 12935 Runolfsdottir Mission, Greenfort, MN 74384-6749

Phone: +16704982844747

Job: Corporate Administration Planner

Hobby: Mountain biking, Jewelry making, Stone skipping, Lacemaking, Knife making, Scrapbooking, Letterboxing

Introduction: My name is Kareem Mueller DO, I am a vivacious, super, thoughtful, excited, handsome, beautiful, combative person who loves writing and wants to share my knowledge and understanding with you.