Renaming files with Python, adding numbering dynamically

0

I have a directory with many pdf lists, and I want to rename the files dynamically.

Ex:

~/teste/

|__ProjMed-Química-Físico.Química-quimica_propriedades_coligativas_exercicios.pdf

|__ProjMed-Química-Físico.Química-quimica_termoquimica_entalpia_lei_de_hess_energia_de_ligacao_exercicios_gabarito.pdf

So far, my code looks like this:

import os
os.chdir('/home/matheus/teste/')
for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    f_id, f_subject, f_frente, f_topic = f_name.split('-')
    f_name1 = '{}-{}-{}-{}{}'.format(f_id, f_subject, f_frente, f_topic, f_ext)
    print(f_name1)
# print(sorted(f_name1, key=str))

As you can see in f_id , there will always be a repeated identifier. in the case of the example, 'ProjMed'.

I would like to count how many ProjMed files appear (total files with this identifier) and rename them so that something looks like this:

1-ProjMed - ***

2-ProjMed - ***

3-ProjMed - ***

etc.

I'm trying to make a script that runs every time a new file is added to a folder. (it would be enabled with Linux incron ) then, day by day, there will be some files that already have a numbering and others that should still have numbering added (always 1 more than the highest value already present in another file). Of course, if there is already a numbered file, it should be ignored at renaming.

How could I modify my current script to achieve these goals?

  • Count how many ' identifiers ' appear per folder ('ProjMed', for example)
  • Ignore the renaming of files that already have numbering
  • Rename unnumbered files with n + 1 , where n is the largest numbering in a file in this folder
asked by anonymous 15.12.2018 / 19:55

0 answers