Renaming files with date in python

Asked

Viewed 611 times

-1

I would like to rename files from one folder and send them to another one, but I wanted it to contain the date or at least put a number after the name if I already had one. The code is this below, but since there are several files I need to change to the same folder, I would change to put the date at the end of the name or an increasing number?

os.rename('C:/scrapy/' + 'conta-completa.pdf','C:/scrapy/teste1/' + 'Teste.pdf')

1 answer

5


My advice is to simply rename increasingly, as putting the date as suffix/prefix (eg dd-mm-yyy_hh:mm:ss) in a cycle like this example would risk many files with equal names (would be changed in the same second or even millisecond):

As a comment I realized that maybe you have to run this over and over again, so you need to get the last one n of the last file changed to rename the first one as (n+1)_foo.pdf:

import os

original_dir = 'caminho/para/pasta/original'
files = os.listdir(original_dir) # todos os ficheiros

last_num = max(int(i.split('_', 1)[0]) for i in files if '_' in i) # ultimo numero
no_changed_files = (i for i in files if '_' not in i) # ficheiros ainda nao mudados
for n, file_name in enumerate(no_changed_files, last_num + 1): # renomear os que ainda nao foram
    full_path = os.path.join(original_dir, file_name)
    if (os.path.isfile(full_path)): # se for ficheiro
        os.rename(full_path, '{}/{}_{}'.format(original_dir, n, file_name))
  • would replace this file_name with the filename between quotes?

  • file_name is already the file name @Guilherme

  • It didn’t work, I’m looking for the.Name a way, using if or for

  • Didn’t work? some error @Uilherme? It would just change in this example the original folders and destination

  • says that src is not declared

  • Bug my @Uilherme, sorry, fixed

  • Opa now changed the name, thank you very much, sorry to abuse, but if I repeat the action he changes the names again and puts and is 1_1_test for example, would not add the 1_ if you already have?

  • Done @William

  • +1 for the effort rs, very good Miguel

  • @Guilherme is made to cover this situation, I’m checking if "_" already exists in the filename

  • was very good, thank you

Show 6 more comments

Browser other questions tagged

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