For explaining a little what comes in all the comments. Your current code was:
import os
def rename_files():
# 1) Vamos a obtener el nombre de los archivos
file_list = os.listdir("D:\prank")
print(file_list)
saved_path = os.getcwd()
print("El directorio activo es " + str(saved_path))
os.chdir("D:\prank")
# 2) Hacemos un bucle que los renombrará uno a uno:
for file_name in file_list :
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path)
rename_files()
Several things.
-
It is not necessary to do func ()
. In fact, it is discouraged to use a space in the call to the function. See here .
-
The variable saved_path
is used within the function, so it is explicitly outside the global scope . To make it available in the scope from where you call it you should define it in scope where you want to use it and you could use global
or nonlocal
but do not I recommend it. Actually you do not use that variable inside the function so it would be ideal if you define it outside the function.
-
When you make the for
you rename everything in file_list
but if there you have things that are not files (directories, for example) they will also be renamed.
-
If you are in Python 3 you could use the pathlib
library to help you in the whole rename process and to take into account if it is a file, directory, link, ...
-
You are using file_name.translate
but that method needs the output of the static str.maketrans
method so you should be giving error.
-
Ideally, the function would accept the path as an argument in such a way that your function would be reusable.
-
In windows you have to be careful when you put paths using \
since if you have, for example, "D:\nueva_carpeta"
, the part with \n
will become a jump line To avoid this you can use the string in the following ways: r"D:\nueva_carpeta"
or "D:\nueva_carpeta"
.
From what I understand, in your code you want to add 0123456789
to each file and I do not know if to each directory in the same folder.
Your transformed code could be something like:
import pathlib
def rename_files(path, rename_dirs = False):
print("El directorio activo es " + str(path))
os.chdir(str(path))
for f in path.iterdir():
if rename_dirs and f.is_dir():
f.rename(str(f) + '_0123456789') # añade _0123456789 al nombre del directorio
if f.is_file():
f.rename(str(f).replace(f.suffix, '_0123456789' + f.suffix)) # añade _0123456789 antes de la extensión del fichero
path = pathlib.Path(r'D:\prank')
rename_files(path)
This solution is only compatible with Python > = 3.4.x. On the labels you have used python-3.x
for what I assume will be worth it. If you use a previous version and do not have many dependencies that prevent you, you should think about updating yourself.
I hope it helps you. If you do not do what you want, please, redo the question to be able to adapt the code.
You can see more about pathlib
in the wonderful blog @astrojuanlu .