Rename files with date in python

-1

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

os.rename('C:/scrapy/' + 'conta-completa.pdf','C:/scrapy/teste1/' + 'Teste.pdf')
    
asked by anonymous 23.10.2018 / 19:32

1 answer

5

My advice is simply to rename it incrementally, because 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 (they would be copied in the same second or even millisecond):

By comment I noticed that you may have to run this several times, so you need to get the last n of the last changed file 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))
    
23.10.2018 / 19:57