HomeComputer SciencePracticalClass 12Text File Remove Duplicate

Class 12 Programs

Quick Tips

  • • Import random module for number generation
  • • Use randint(1, 6) for dice simulation
  • • Handle user input validation properly

Text File Remove Duplicate

AIM

To write a Python program to remove duplicate lines from a text file.

ALGORITHM

  1. Start
  2. Open the input text file in read mode.
  3. Read all lines from the file and store them in a set to remove duplicates.
  4. Open a new output text file in write mode.
  5. Write the unique lines from the set to the output file.
  6. Close both files.
  7. Stop

PROGRAM

# Python program to remove duplicate lines from a text file

def remove_duplicates(input_file, output_file):
    with open(input_file, 'r') as file:
        lines = file.readlines()
    
    unique_lines = set(lines)
    
    with open(output_file, 'w') as file:
        file.writelines(unique_lines)

# Example usage
remove_duplicates('input.txt', 'output.txt')

OUTPUT

Unique lines from the input file are written to the output file.

CONCLUSION

Thus, the given program was successfully executed and the output was verified as per the expected result.

VIVA QUESTIONS

  1. What are arithmetic operators in Python?

    Arithmetic operators are symbols used to perform mathematical operations: +, -, *, /, %, //, and **.

  2. How do you remove duplicates from a file?

    You can remove duplicates from a file by reading all lines, storing unique lines using a set or dictionary, and writing them to a new file.