I am studying Python is a very good place called Coding Nomads, as part of one of my assignments I have to make post about one of my automation homeworks. In this case the goal was to make a program that takes all the given files of a directory (given in the code) and rename the files using a counter; all this using the module pathlib. So this is my code:
import pathlib
folder=pathlib.Path("C:/Users/Amma/Desktop/Coding Nomads/python-101-main/13_modules-and-automation/Example for rename")
a=1
for file in folder.iterdir():
old_name=file.stem
old_ext=file.suffix
c=file.suffix
new_stem=f"This is the file {a} and now the format is {c}"
new_name=new_stem+old_ext
file.rename(pathlib.Path(folder,new_name))
a+=1
I do find one error, is when you open one of the files that you will rename, so the program is not able to rename that file and give the next error:
PermissionError: [WinError 32] El proceso no tiene acceso al archivo porque está siendo utilizado por otro proceso: 'C:\\Users\\Amma\\Desktop\\Coding Nomads\\python-101-main\\13_modules-and-automation\\Example for rename\\This is the file 7 and the format is .docx.docx' -> 'C:\\Users\\Amma\\Desktop\\Coding Nomads\\python-101-main\\13_modules-and-automation\\Example for rename\\This is the file 23 and now the format is .docx.docx'
In this case, effectively I opened and modify the file “This is the file 7 and the format is .docx.docx'”
The directory there is the one I used as example, but please feel free to try in your pc if you want and post me if you had any problem, also if there is something this code can get better; I will appreciate it.
Top comments (0)