Reputation: 907
I would like to build a python script to do the following
change all occurrences of "bla" to "abd" in the file names.
For instance:
123_bla.dd -> 123_abd.dd
bla.dd -> _abd.dd
How can I do that?
I tried:
for fn in os.listdir("."):
print fn # test
if fnmatch.fnmatch(fn, '*bla*'):
fn = fn.replace(fn, "abd")
print fn
Upvotes: 0
Views: 227
Reputation: 14261
You're just changing the string containing the files' names, not the actual filenames. Try using os.rename()
for fn in os.listdir("."):
print fn # test
if fnmatch.fnmatch(fn, "bla):
fixed = fn.replace("bla", "abd")
os.rename(fn, fixed)
Upvotes: 0
Reputation: 4176
You are just getting the names of the files in strings and then renaming them, you need to rename the files using the os.rename()
method.
Upvotes: 0
Reputation: 3947
You have to use the replace
method correctly: https://docs.python.org/2/library/string.html#string.replace
You have to do fn.replace('bla', 'abd')
. And then of course do the actual renaming https://docs.python.org/2/library/os.html#os.rename
Upvotes: 2