Renaming bulk files from a notepad list

Asked

Viewed 1,396 times

0

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

Example of how the notepad:

*nomeantigo1;nomenovo1*

*nomeantigo2;nomenovo2*

*nomeantigo3;nomenovo3*

At first the code runs straight replacing the names, mainly in smaller folders with few photos. But in larger folders it starts to rotate partially and sometimes it doesn’t even rotate!

I don’t know if it’s some logic error in the loop or some system permission!

As there are many files I am running code directly on 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 am beginner in programming!

Thank you in advance

  • The names of the files that are in this txt are from the same directory?

  • yes, I’m running everything in the same directory!

1 answer

1

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 on Repl.it

That is, go through all the lines of the file that has the names of the files and rename one by one.

  • Your code is cleaner and shorter, but it keeps giving the same result as mine! (mine dealt with file extensions as well) Now I saw that it stops renaming when it finds in the list a file that has already been renamed or is not in the same folder, because I run the same script and same list in several folders, it is all in one. Would you know how to tell me how to keep loop running even after giving an "error" to "X file not found in folder"?

Browser other questions tagged

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