Cambiar el nombre de los archivos y ordenarlos después de la fecha de creación

I have a lot of files in a specific directory and I want to rename all files with the extension type .txt after the file creation date and add a counter prefix. By the way, I'm using python on windows.


Digamos que tengo los archivos aaa.txt, bbb.txt y ccc.txt.

aaa.txt is the newest file and ccc.txt ist the oldest created file.

I want to rename the files that way:

999_aaa.txt, 998_bbb.txt, 997_ccc.txt ...

The counter should start with 999_newest file (I will never have more than 300 txt file). Like you can see I just want to give the newest file the highest number (sorted by creation date).

¿Cómo harías esto?

preguntado el 13 de septiembre de 13 a las 12:09

Actually I have a working code thats really ugly. Within a for loop I increased a counter but I was not able to start from 999. -

So include your code. -

1 Respuestas

Have a look at this untested code:

import os
import glob
import shutil

# get a list of all txt files
fnames = glob.glob("*.txt")
# sort according to time of last modification/creation (os-dependent)
# reverse: newer files first
fnames.sort(key=lambda x: os.stat(x).st_ctime, reverse=True)
# rename files, choose pattern as you like
for i, fname in enumerate(fnames):
    shutil.move(fname, "%03d_%s" % (999-i, fname))

Para referencia:

Respondido el 13 de Septiembre de 13 a las 13:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.