0

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.

Ajinkya
  • 1,797
  • 3
  • 24
  • 54

3 Answers3

2

Perhaps you are intending to do os.rename("./12/" + file, ./12/" + r)? As you are modifying the files in the directory named 12, not the directory where the Python script was executed from.

RealPawPaw
  • 988
  • 5
  • 9
  • Does this work? I do not have the same directory structure as yours so I am unable to tell. – RealPawPaw Nov 15 '19 at 05:27
  • I tried cwd=os.getcwd() \ os.rename(os.path.join(cwd,file), os.path.join(cwd,r)) but I get this error: [Errno 2] No such file or directory: '/home/ajinkya/Desktop/123/ab 1.jpg' -> '/home/ajinkya/Desktop/123/ab__1.jpg' Where as in reality this directory exists – Ajinkya Nov 15 '19 at 05:27
0

Use os.rename(file, r) instead of os.rename(r, file).

Corentin Pane
  • 4,794
  • 1
  • 12
  • 29
jetprop
  • 76
  • 3
  • It gives the same error: /home/ajinkya/Desktop/123 Traceback (most recent call last): File "demo.py", line 9, in os.rename(file, r) FileNotFoundError: [Errno 2] No such file or directory: 'ab 1.jpg' -> 'ab__1.jpg' ajin – Ajinkya Nov 15 '19 at 05:16
0

My bad I had to provide absolute path to rename these files:

import os
cwd=os.getcwd()+'/12'
print(cwd)


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(os.path.join(cwd,file), os.path.join(cwd,r))
Ajinkya
  • 1,797
  • 3
  • 24
  • 54