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
ROI Calculator - Return on Investment Calculator
Credit Risk | How to Measure Credit Risk with Types and Uses?
Ou Football Brainiacs
FREE Houses! All You Have to Do Is Move Them. - CIRCA Old Houses
Teacup Yorkie For Sale Up To $400 In South Carolina
Dragon’s Dogma 2 Gets New Casual Mode and More Improvements Ahead of PS5 Pro Enhanced Patch - IGN
Mobile Patrol Prentiss County Ms
Craigslist Cars For Sale Rochester Ny
062203010
Houses for Rent in Sarasota-Bradenton, FL - 183 Rental Homes | Zumper
Restored Republic June 6 2023
Siemens söker Business Controller Siemens i Solna | LinkedIn
Netronline Historic Aerials
Choose the antonym of the given word- Rarely a) Hardly b) Frequentlyc) Definitelyd) Absolutely
Caroline G. Atkinson Intermediate School
Tom DiVecchio - LILLY BROADCASTING | LinkedIn
los angeles cars & trucks - by owner "used cars" - craigslist
Lynn Gruson
Anime Feet Blogspot
Why Did Mountain Creek Mud Bog Close
9Xflix Movie
Meg 2: The Trench Showtimes Near Phoenix Theatres Laurel Park
Yale College Confidential 2027
For Black Boys review: A poignant meditation on black masculinity and mental health
Death Note: 15 Details About L You'd Only Know If You Read The Manga
Alexa Liquor Barn Toledo Oh
Best Breakfast Near Grand Central Station New York
Ff14 Sit Anywhere
Harvestella Sprinkler Lvl 2
Skyward Riverton Il
How promising student was drawn into gangland world and went on to viciously ‘kill 17’ and brag about crimes online - before being murdered at 17
Last Cloudia Radiance Of The World
Santa Cruz Craigslist Cars And Trucks - By Owner
Labor Gigs On Craigslist
Bistró Cuban Cafe Reviews
Snaccavellie
Pick34 Free Zone
City Demands Pastor Take Down 'Jesus' Sign in Front of Church, Gets Epic Response from Him During Sermon
Nba Draftkings Picks For Tonight Cbs
Ati Nurses Touch The Leader Case 4
How Greg Gutfeld Turned Fox News Channel Into A Late-Night Ratings Juggernaut
Bofa Drive Thru Near Me
Gander Rv Hamburg Ny
Jodie Sweetin Breast Reduction
Point2 Homes Costa Rica
Goanimate Gina Delgado
Savage Foolsbaby
Lids Locker Room Vacaville Photos
Is Nadav In Rehab
Drift Boss 911
Biscotti Gushers | Marijuana Strain Reviews
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.