I am having a problem with this code. I am trying to rename all of the filenames within a folder so that they no longer have +'s
in them! This has worked many times before but suddenly I get the error:
WindowsError: [Error 2] The system cannot find the file specified at line 26
Line 26 is the last line in the code.
Does anyone know why this is happening? I just promised someone I could do this in 5 minutes because I had a code! Shame it doesnt work!!
import os, glob, sys
folder = "C:\\Documents and Settings\\DuffA\\Bureaublad\\Johan\\10G304655_1"
for root, dirs, filenames in os.walk(folder):
for filename in filenames:
filename = os.path.join(root, filename)
old = "+"
new = "_"
for root, dirs, filenames in os.walk(folder):
for filename in filenames:
if old in filename:
print (filename)
os.rename(filename, filename.replace(old,new))
You are using
splitext
to determine the source filename to rename:If you encounter a file with an extension, obviously, trying to rename the filename without the extension will lead to a "file not found" error.
I suspect that you may be having issues with subdirectories.
If you have a directory with files "
a
", "b
" and subdirectory "dir
" with files "sub+1
" and "sub+2
", the call toos.walk()
will yield the following values:When you process the second tuple, you will call
rename()
with'sub+1', 'sub_1'
as the arguments, when what you want is'dir\sub+1', 'dir\sub_1'
.To fix this, change the loop in your code to:
which will concatenate the directory with the filename before you do anything with it.
Edit:
I think the above is the right answer, but not quite the right reason.
Assuming you have a file "
File+1
" in the directory,os.walk()
will returnUnless you are in the "
10G304655_1
" directory, when you callrename()
, the file "File+1
" will not be found in the current directory, as that is not the same as the directoryos.walk()
is looking in. By doing the call toos.path.join()
yuo are telling rename to look in the right directory.Edit 2
A example of the code required might be: