Rename python files using Excel list

Asked

Viewed 76 times

1

I am trying to perform the following function: Rename a list of files according to their modification date, from the oldest to the newest. The name of the files I have in an Excel list and the intention is to rename the oldest file with the 1st line of excel, second oldest file with the 2nd line of Excel. The code I have today renames only a random file with the first line and after the error:

import pandas as pd
import os
from datetime import datetime
#lista dos links
urls = pd.read_excel(r'C:/Users/u0000008/Documents/Excel/Controle de Janelas - Comissões - 2a Janela.xlsm', sheet_name ='Respostas',)

path = r'C:\Users\u0000008\Downloads'
files = os.listdir(path)
mod_time = os.path.getmtime(r'C:\Users\u0000008\Downloads')
print(datetime.fromtimestamp(mod_time))
lista_nomes =[] 
for Nome, file in enumerate(files):
    lista_nomes =[] 
    for Nome in urls ['Digite e selecione o nome ou o código de seu escritório abaixo:']:
        os.rename(os.path.join(path, file), os.path.join(path, ''.join([str(Nome), '.pdf'])))
        

1 answer

0

I didn’t consider your example of code for the answer. I suggest you review the code structure.

I attend to the problem defined as:

Rename a list of files according to the modification date of them, being from the oldest to the newest. The name of the files i have in an Excel list and the intention is to rename the file more old with the 1st line of excel, second oldest file with the 2nd excel line.

My solution suggestion is as below:

import pandas as pd
import os

folder = "D:\\Downloads\\teste\\"
f = pd.read_excel("D:\\Desktop\\nomes_arquivos.xlsx")

# conteúdo do arquivo excel:
print(f)

       0
0  Arq01
1  Arq02
2  Arq03
3  Arq04
4  Arq05

# conteudo do diretório com os arquivos:
for name in os.listdir(folder):
    print(name)

file01.txt
file02.txt
file04.txt
file05.txt
file10.txt

# gero uma lista com o par: (nome_arquivo, mtime)
L = [tuple([item, os.path.getmtime(folder + item)]) for item in os.listdir(folder)]

# ordeno a lista utilizando o mtime como chave
L.sort(key=lambda x: x[-1])

# reduzo a lista apenas aos nomes dos arquivos, na ordem acima
L = [item[0] for item in L]

# gero uma lista com os nomes dos arquivos
nomes = list(f[0])

# utilizo zip() para construir o rename

# observação importante: os arquivos renomeados estarão no diretório de origem, e não no diretório do arquivo com a lista de nomes

for velho, novo in zip(L, nomes):
    os.rename(os.path.join(folder, velho), os.path.join(folder, ''.join([novo, '.pdf'])))

I suggest reading that article on how to prepare a good question.

Browser other questions tagged

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