I have a folder named '12' and this folder contains following files:
import os
for root, dirs, files in os.walk('./12', topdown=True):
dirs.clear() #with topdown true, this will prevent walk from going into subs
for file in files:
print(file)
Output:
ab 1.jpg
ab 0.jpg
Now I want to replace spaces in the above files with an underscore to do this I have done:
import os
for root, dirs, files in os.walk('./12', topdown=True):
dirs.clear() #with topdown true, this will prevent walk from going into subs
for file in files:
r=file.replace(" ", "_")
os.rename(r, file)
In the above code when I print(r)
it gives me value of space replaced by underscore i.e
ab__1.jpg
ab_0.jpg
But the os.rename function does not work and actual file names are not changed inside the folder. I get the following error for os.rename(r, file):
Traceback (most recent call last): File "demo.py", line 7, in os.rename(r, file) FileNotFoundError: [Errno 2] No such file or directory: 'ab__1.jpg' -> 'ab 1.jpg'
How can I resolve this error ?
Edit: My question is not a duplicate of Rename multiple files in a directory in Python because on the mentioned link they are using one for loop to recursively rename all the files in the current working directory. In my question I am using 2 for loops as renaming files is one sub part of my entire process, When I use two for loops I am encountering my error.