Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Find Unique Lines From Two Text Files
Next article icon

Python Program to Find Unique Lines From Two Text Files

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will discuss finding unique lines from two text files and storing them using Python. To understand the concept we will take the two text file and read the file and find the unique line based on conditions and append it to another file. So, let's understand the implementation of the code as below:

The first text file:

 

The second text file:

 

The unique lines between them are:

DSA Self-paced

System Design Live

Stepwise Implementation

Step 1: In the first step we will open both text files in "read " mode using the Python open() function and read all the lines of the file1 and file2(gfg1.txt, gfg2.txt) using the Python readlines() function and the corresponding data is stored in a variable 'a' and 'b'.

a = open('gfg1.txt', 'r').readlines()
b = open('gfg2.txt', 'r').readlines()

Step 2: Another variable 'output' is created to store the unique lines between both files.

output = []

Step 3: Now, the second text file is traversed using a for loop, and for every input, a condition is checked whether the given sentence is present in the first text file or not. If the condition is true then the sentence is appended to the list.

for item in b:
if item not in a:
output.append(item)

Step 4: A new file says 'resultant' is opened in write mode. The list is traversed using for loop and all the corresponding lines are written in the 'resultant' file using the Python write() function.

with open('resultant.txt', 'w') as res:
for line in output:
res.write(line)

Step 5: Now, we can open the resultant file in our local directory to see the unique line among both files.

Code Implementation

Python
a = open('gfg1.txt', 'r').readlines() b = open('gfg2.txt', 'r').readlines() output = []  for item in b:     if item not in a:         output.append(item)  with open('resultant.txt', 'w') as res:     for line in output:         res.write(line) 

Output:

 

Method-2:

One alternative approach you could use to find the unique lines between two text files is to use the set data type. A set is an unordered collection of unique elements in Python, which means that it does not allow duplicate elements and does not preserve the order of the elements.

You can use a set to store the lines from one of the text files, and then use the difference method to find the lines that are not present in the other text file. Here is an example of how you could use this approach:

Python
# Open the first text file in write mode with open('gfg1.txt', 'w') as file1:     # Write the additional content to the first text file     file1.write("GeeksforGeeks\nSandeep Jain Sir\n")  # Close the first text file file1.close()  # Open the second text file in write mode with open('gfg2.txt', 'w') as file2:     # Write the additional content to the second text file     file2.write("GeeksforGeeks\nSandeep Jain Sir\nDSA Self-paced\nSystem Design Live     ")  # Close the second text file file2.close()  # Open the first text file in read mode with open('gfg1.txt', 'r') as file1:     # Read the lines from the first text file     lines1 = file1.readlines()  # Convert the lines from the first text file to a set lines1_set = set(lines1)  # Open the second text file in read mode with open('gfg2.txt', 'r') as file2:     # Read the lines from the second text file     lines2 = file2.readlines()  # Convert the lines from the second text file to a set lines2_set = set(lines2)  # Find the unique lines between the two text files unique_lines = lines2_set.difference(lines1_set)  # Iterate over the unique lines and print them for line in unique_lines:     print(line) 

This will find the unique lines between the two text files .

Output:

DSA Self-paced

System Design Live  

Steps:

  1. Open the first text file in "write" mode using the open function.
  2. Write the content to the first text file using the write method.
  3. Close the first text file using the close method.
  4. Open the second text file in "write" mode using the open function.
  5. Write the additional content to the second text file using the write method.
  6. Close the second text file using the close method.
  7. Open the first text file in "read" mode using the open function.
  8. Read the lines from the first text file using the readlines method.
  9. Convert the lines from the first text file to a set data type.
  10. Open the second text file in "read" mode using the open function.
  11. Read the lines from the second text file using the readlines method.
  12. Convert the lines from the second text file to a set data type.
  13. Find the unique lines between the two text files using the difference method on the sets.
  14. Iterate over the unique lines using a for loop, and print each line using the print function.

Next Article
Python Program to Find Unique Lines From Two Text Files

R

raj2002
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Python Programs
  • Technical Scripter 2022
  • python-file-handling
  • Python-string-functions
Practice Tags :
  • python

Similar Reads

    Python Program to Find the Number of Unique Words in Text File
    Given a text file, write a python program to find the number of unique words in the given text file in Python.Examples:Input: gfg.txtOutput: 18Contents of gfg.txt: GeeksforGeeks was created with a goal in mind to provide well written well thought and wellexplained solutions for selected questionsExp
    2 min read
    Find Unique Elements from Tuple in Python
    Tuples are immutable built-in data type in Python that can store multiple values in it. Extracting Unique Elements from a Tuple in Python can be done through two different approaches. Examples: Input: (1, 2, 13, 4, 3, 12, 5, 7, 7, 2, 2, 4)Output: (1, 2, 3,4,5,12,13)Input: ('Apple', 'Mango', 'Banana'
    5 min read
    Python Program to Print uncommon elements from two sorted arrays
    Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50} Output : 10 25 40 50 We do not print 20 and 30 as these elements ar
    3 min read
    Python | Merge two text files
    Given two text files, the task is to merge the data and store in a new text file. Let's see how can we do this task using Python. To merge two files in Python, we are asking user to enter the name of the primary and second file and make a new file to put the unified content of the two data into this
    2 min read
    Python program to Count the Number of occurrences of a key-value pair in a text file
    Given a text file of key-value pairs. The task is to count the number of occurrences of the key-value pairs in the file with PythonProgram to Count the occurrences of a key-value pairNaive Approach to Count the Occurrences of a key-value PairUsing Python built-in collections.CounterUsing regular exp
    3 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