[FIXED] How can I write a Python Script that helps me check if there are any duplicates in my directory? Duplicate files have the same subject key

Issue

I cannot write the usual script for checking duplicates in this case. I will need to filter out duplicates based only on their subject key. The file naming convention is like this,

DD-MM-YY-SubjectKey-location.txt

06-12-78-7677-home.txt
28-11-98-1561-home.txt
14-06-90-8888-work.txt
30-01-06-7677-work.txt

In my case, these two files are duplicates as they have the same subject id.

06-12-78-7677-home.txt
30-01-06-7677-work.txt

Edit: Also, if I could delete all the duplicates, but one.


Solution

here with a safe delete (sends to trash/recycle bin)

import os
import re
import send2trash

files = os.listdir(os.getcwd())
subject_store = set()
for file in files:
    if re.search('\d\d-\d\d-\d\d-\w*-\w*.txt', file):
        subject = file.split('-')[3]
        if subject in subject_store:
            try:
                print(f"deleting {file}")
                send2trash.send2trash(os.path.join(os.getcwd(), file))
            except Exception as e:
                print(e)
        else:
            subject_store.add(subject)


Answered By - Kapil
Answer Checked By - Robin (Python.Easybugfix Admin)

Related Posts

Post a Comment