Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data preprocessing
  • Data Manipulation
  • Data Analysis using Pandas
  • EDA
  • Pandas Exercise
  • Pandas AI
  • Numpy
  • Matplotlib
  • Plotly
  • Data Analysis
  • Machine Learning
  • Data science
Open In App
Next Article:
Compare Two Xml Files in Python
Next article icon

Compare Two Csv Files Using Python

Last Updated : 30 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

file1.csv contains

Name,Age,City
John,25,New York
Emily,30,Los Angeles
Michael,40,Chicago

file2.csv contains

Name,Age,City
John,25,New York
Michael,45,Chicago
Emma,35,San Francisco

Using compare()

compare() method in pandas is used to compare two DataFrames and return the differences. It highlights only the rows and columns where the values differ, making it ideal for structured data comparison.


Python
import pandas as pd  df1 = pd.read_csv('file1.csv') df2 = pd.read_csv('file2.csv')  # Compare DataFrames res = df1.compare(df2) print(res) 

Output

Output
Using compare()

Explanation: It first reads file1.csv and file2.csv into two separate DataFrames, df1 and df2. The compare() method is then applied to identify differences between the two DataFrames.

Using set operations

This method reads both files line-by-line and stores their content as sets. Using set difference (a - b) allows you to quickly identify lines that are present in one file but not the other.

Python
with open('file1.csv') as f1, open('file2.csv') as f2:     a = set(f1.readlines())     b = set(f2.readlines())  print(a - b) print(a - b) 

Output

Output
Using set operations

Explanation: It first opens file1.csv and file2.csv, reads their contents line by line and stores them as sets a and b. The difference a - b is then printed to show lines present in file1.csv but not in file2.csv.

Using difflib

Python’s difflib module provides detailed differences between files, similar to Unix's diff command. It can generate unified or context diffs showing what was added, removed, or changed.

Python
import difflib  with open('file1.csv') as f1, open('file2.csv') as f2:     d = difflib.unified_diff(f1.readlines(), f2.readlines(), fromfile='file1.csv', tofile='file2.csv')     for line in d:         print(line, end='') 

Output

Output
Using difflib

Explanation: It opens file1.csv and file2.csv, reads their contents, and uses difflib.unified_diff() to generate a line-by-line comparison. The output shows added, removed or changed lines between the two files in a unified diff format.


Next Article
Compare Two Xml Files in Python
author
susobhanakhuli
Improve
Article Tags :
  • Python
  • Python Programs
  • Python-pandas
  • python-csv
Practice Tags :
  • python

Similar Reads

  • How To Create A Csv File Using Python
    CSV stands for comma-separated values, it is a type of text file where information is separated by commas (or any other delimiter), they are commonly used in databases and spreadsheets to store information in an organized manner. In this article, we will see how we can create a CSV file using Python
    3 min read
  • Compare Two Xml Files in Python
    We are given two XML files and our task is to compare these two XML files and find out if both files are some or not by using different approaches in Python. In this article, we will see how we can compare two XML files in Python. Compare Two XML Files in PythonBelow are the possible approaches to c
    3 min read
  • Convert CSV to JSON using Python
    Converting CSV to JSON using Python involves reading the CSV file, converting each row into a dictionary and then saving the data as a JSON file. For example, a CSV file containing data like names, ages and cities can be easily transformed into a structured JSON array, where each record is represent
    2 min read
  • How to Add Numbers in a Csv File Using Python
    When working with CSV files in Python, adding numbers in the CSV file is a common requirement. This article will guide you through the process of adding numbers within a CSV file. Whether you're new to data analysis or an experienced practitioner, understanding this skill is vital for efficient data
    3 min read
  • How to compare two lists in Python?
    In Python, there might be a situation where you might need to compare two lists which means checking if the lists are of the same length and if the elements of the lists are equal or not. Let us explore this with a simple example of comparing two lists. [GFGTABS] Python a = [1, 2, 3, 4, 5] b = [1, 2
    3 min read
  • Python | Compare tuples
    Sometimes, while working with records, we can have a problem in which we need to check if each element of one tuple is greater/smaller than it's corresponding index in other tuple. This can have many possible applications. Let's discuss certain ways in which this task can be performed. Method #1 : U
    4 min read
  • How to Compare Two Iterators in Python
    Python iterators are powerful tools for traversing through sequences of elements efficiently. Sometimes, you may need to compare two iterators to determine their equality or to find their differences. In this article, we will explore different approaches to compare two iterators in Python. Compare T
    3 min read
  • Convert Dict of List to CSV - Python
    To convert a dictionary of lists to a CSV file in Python, we need to transform the dictionary's structure into a tabular format that is suitable for CSV output. A dictionary of lists typically consists of keys that represent column names and corresponding lists that represent column data.For example
    4 min read
  • Exporting Multiple Sheets As Csv Using Python
    In data processing and analysis, spreadsheets are a common format for storing and manipulating data. However, when working with large datasets or conducting complex analyses, it's often necessary to export data from multiple sheets into a more versatile format. CSV (Comma-Separated Values) files are
    3 min read
  • How to Compare Two Dictionaries in Python
    In this article, we will discuss how to compare two dictionaries in Python. The simplest way to compare two dictionaries for equality is by using the == operator. Using == operatorThis operator checks if both dictionaries have the same keys and values. [GFGTABS] Python d1 = {'a': 1, 'b
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences