Automatizar tareas aburridas
Renombrar 300 archivos a mano toma una tarde. Con Python toma tres líneas y dos segundos.
Automating boring tasks
Renaming 300 files by hand takes an afternoon. With Python it takes three lines and two seconds.
El módulo os —ya lo usaste en el tutorial de módulos— habla directamente con
el sistema de archivos. os.listdir() te da la lista de lo que hay en una
carpeta.
The os module — you already used it in the modules tutorial — talks directly
to the file system. os.listdir() gives you the list of what is in a folder.
Con lo que sabes de comprensión de listas y .endswith(), quedarte solo con
un tipo de archivo es una línea.
With what you know about list comprehensions and .endswith(), keeping only
one file type is a single line.
Fíjate en .lower() antes de .endswith():
así "foto1.JPG" y "foto2.jpg" se detectan igual, sin importar
mayúsculas.
Note .lower() before .endswith(): that
way "foto1.JPG" and "foto2.jpg" are detected the same, regardless
of case.
os.rename(nombre_viejo, nombre_nuevo) renombra un archivo. Combinado con un
bucle y enumerate() —numera automáticamente cada vuelta—, puedes ordenar cientos
de archivos de una vez.
os.rename(old_name, new_name) renames a file. Combined with a loop and
enumerate() — automatically numbers each pass — you can sort hundreds of files
at once.
Un consejo que te va a ahorrar un disgusto: antes de renombrar o borrar algo de verdad, imprime lo que harías, sin ejecutarlo todavía.
Advice that will save you grief: before renaming or deleting anything for real, print what you would do, without running it yet.
os.listdir(), filtrar por extensión, os.rename() con
enumerate(), y el hábito de simular antes de ejecutar algo irreversible.
Ya sabes manejar datos y archivos. Para terminar esta parte, hagamos que esos datos se vean.
os.listdir(), filtering by extension, os.rename() with
enumerate(), and the habit of simulating before running anything irreversible.
You already know how to handle data and files. To close this part, let us make that data visible.