Equal names different file extensions

Asked

Viewed 50 times

-4

I have a directory with 2000 files, many have the same name and different extension, ex: diff001.txt diff001.pdf diff003.txt diff013.txt diff014.pdf diff021.txt diff021.pdf in this case I would like to keep only the file with the txt extension and delete the pdf.

I have no idea how to do it. Thank you.

  • Isn’t it easier to make OS? For example from zsh: rm -- *.pdf(e'{[ -e $REPLY:r.txt]}')

1 answer

-3


There are several ways to do it, follow one of them:

import os

path = 'COLOQUE_AQUI_O_PATH_PARA_DIRETORIO_COM_ARQUIVOS'

txt_files = [f for f in os.listdir(path) if f.endswith('txt') and os.path.isfile(os.path.join(path, f))]

This form above comprehensilist on amounts to:

txt_files = []

for f in os.listdir(path):
     if f.endswith('txt') and os.path.isfile(os.path.join(path, f):
         txt_files.append(f)

Note This solution does not take subdirectories into account as it was not requested in the question

  • For those who voted negative, could explain why I improve the answer?

  • I did not vote either in the question or in the answers, I only closed because it is not a programming problem because this activity is solved with a line in a terminal, maybe the most verbose line is in the power shell but still a line. And maybe that’s why the negatives.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.