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 to os.walk()
will yield the following values:
(('.',), ('dir',), ('a', 'b'))
(('dir',), (,), ('sub+1', 'sub+2'))
When you process the second tuple, you will call rename()
with 'sub+1', 'sub_1'
as the arguments, when what you want is 'dirsub+1', 'dirsub_1'
.
To fix this, change the loop in your code to:
for root, dirs, filenames in os.walk(folder):
for filename in filenames:
filename = os.path.join(root, filename)
... process file here
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 return
("C:/Documents and Settings/DuffA/Bureaublad/Johan/10G304655_1/", (,), ("File+1",))
Unless you are in the "10G304655_1
" directory, when you call rename()
, the file "File+1
" will not be found in the current directory, as that is not the same as the directory os.walk()
is looking in. By doing the call to os.path.join()
yuo are telling rename to look in the right directory.
Edit 2
A example of the code required might be:
import os
# Use a raw string, to reduce errors with characters.
folder = r"C:Documents and SettingsDuffABureaubladJohan10G304655_1"
old = '+'
new = '_'
for root, dirs, filenames in os.walk(folder):
for filename in filenames:
if old in filename: # If a '+' in the filename
filename = os.path.join(root, filename) # Get the absolute path to the file.
print (filename)
os.rename(filename, filename.replace(old,new)) # Rename the file