Rename Bulk Files from a Notepad List

0

I need to rename many (many !!!) photos inside some folders, so I decided to use the os.rename method inside a loop from an auxiliary list in the notepad that contains in each line the old name of the photo, and a semicolon separating for which is the new name of each one.

Example of how notepad is:

*nomeantigo1;nomenovo1*

*nomeantigo2;nomenovo2*

*nomeantigo3;nomenovo3*

At first the code runs right replacing the names, especially in smaller folders with few photos. But in larger folders it starts to run partially and sometimes does not spin!

I do not know if it's some logic bug in the loop or some system permission!

How many files am I running the code direct on the external hard drive, and using Python 3.6.5 on Windows 10

My code:

import os
import string
import re
from os import rename
from os import replace
from os import listdir

lista_principal = os.listdir('.')
arquivo = open('lista_auxiliar.txt')
sublista = [linha.strip() for linha in arquivo]
arquivo.close()

nome_antigo = list()
nome_novo = list()
nomeacoes = list()
nomeacoes_separadas = list()

for i in range(len(sublista)):
    nomeacoes.append(sublista[i].split(';'))

for i in range(len(nomeacoes)):
    if (type(nomeacoes[i]) is list):
        nomeacoes_separadas = nomeacoes[i];
        nome_antigo.append(nomeacoes_separadas[0])
        nome_novo.append(nomeacoes_separadas[1])

for nome in lista_principal:
    nome_tratado = nome.split('.jpg')
    nome_tratado_teste = str(nome_tratado[0])
    for i in range(len(nome_antigo)):
        if nome_tratado_teste == nome_antigo[i]:
            os.rename(nome, str(nome_novo[i]) + '.jpg')

Sorry if the logic is not very clean, I'm a beginner in programming!

Thank you in advance

    
asked by anonymous 27.04.2018 / 17:36

1 answer

0

If I understand correctly, what you need to do is just:

import os

with open('nomes.txt') as nomes:
    for nome in nomes:
        antigo, novo = nome.strip().split(';')
        os.rename(antigo, novo)
        print(f'Arquivo {antigo} renomeado para {novo}')

See working at Repl.it

That is, it traverses all the lines of the file that has the file names and renames them one by one.

    
27.04.2018 / 18:21