Search code examples
python-3.xfile

Deleting files if duplicated names isn't epub or kepub


So I downloaded tons of ebooks from telegram, and now I have tons of files im different formats as well. So I would like to remove the duplicates (if any) and keep only the 'epub' or 'kepub' format from that ebook 'copy'. That part I figure it out, but when it's not a 'copy' I want to keep the file 'pdf' or whatever format.

import os

diretorio = '/home/jcsantos/Desktop/teste_ebook'


def apagar_ficheiros(diretorio):
    ficheiros_por_nome = {}

    for ficheiro in os.listdir(diretorio):
        nome, ext = os.path.splitext(ficheiro)
        if ext not in ['.epub', '.kepub']:
            if nome not in ficheiros_por_nome:
                ficheiros_por_nome[nome] = []            
            ficheiros_por_nome[nome].append(ficheiro)
    
    for ficheiros in ficheiros_por_nome.values():
        for ficheiro in ficheiros:
            caminho = os.path.join(diretorio, ficheiro)
            print(f'Apagando: {caminho}')
            os.remove(caminho)


apagar_ficheiros(diretorio)

The list:

(20240824-PT) Fugas Público.pdf
1_384198847695421742.pdf
01. FOURTH WING by Rebecca Yarros.epub
01. Gone - O Mundo Termina Aqui - Michael Grant.epub
01.A Escola do Bem e do Mal - Soman Chainani.epub
01.A Escola do Bem e do Mal - Soman Chainani.mobi
01.A Escola do Bem e do Mal - Soman Chainani.pdf
1. As Mentiras de Locke – Scott Lynch.epub
1. Eu sei o que você está pensando – John Verdon.epub
1. Eu sei o que você está pensando – John Verdon.mobi
1. Eu sei o que você está pensando – John Verdon.pdf
1. O Amante - Jodi Ellen Malpas.azw3
1. O Amante - Jodi Ellen Malpas.epub
1. O Amante - Jodi Ellen Malpas.mobi
1. O Amante - Jodi Ellen Malpas.pdf
1. Tess Gerritsen (Rizzoli & Isles) - O Cirurgiao.epub

What I want to keep after program delete the duplicated:

(20240824-PT) Fugas Público.pdf
1_384198847695421742.pdf
01. FOURTH WING by Rebecca Yarros.epub
01. Gone - O Mundo Termina Aqui - Michael Grant.epub
01.A Escola do Bem e do Mal - Soman Chainani.epub
1. As Mentiras de Locke – Scott Lynch.epub
1. Eu sei o que você está pensando – John Verdon.epub
1. O Amante - Jodi Ellen Malpas.epub
1. Tess Gerritsen (Rizzoli & Isles) - O Cirurgiao.epub

I expect that keeps the files that don't have any copy


Solution

  • You could at first create a dict where the keys represent the filenames and the values are a list of existing file extensions:

    from pathlib import Path
    
    files = {}
    
    for x in Path(".").iterdir():
        if x.is_file():
            files.setdefault(x.stem, []).append(x.suffix)
    print(files)
    

    Output:

    {'1. Eu sei o que você está pensando – John Verdon': ['.pdf',
      '.epub',
      '.mobi'],
     '01.A Escola do Bem e do Mal - Soman Chainani': ['.epub', '.mobi', '.pdf'],
     '1. Tess Gerritsen (Rizzoli & Isles) - O Cirurgiao': ['.epub'],
     '1. O Amante - Jodi Ellen Malpas': ['.pdf', '.azw3', '.epub', '.mobi'],
     '(20240824-PT) Fugas Público': ['.pdf'],
     '1_384198847695421742': ['.pdf'],
     '1. As Mentiras de Locke – Scott Lynch': ['.epub'],
     '01. FOURTH WING by Rebecca Yarros': ['.epub'],
     '01. Gone - O Mundo Termina Aqui - Michael Grant': ['.epub']}
    

    After that you loop through that list and delete all filenames that exist several times and use a custom sort to keep the file extension you prefer:

    def custom_sort(suffix):
        priorities = {'.epub':1, '.kepub':2, '.pdf':3}
        return priorities.get(suffix, 4)   
    
    for n,s in files.items():
        for x in sorted(s, key=custom_sort)[1:]:
            Path(n+x).unlink()