John John - 1 month ago 9
Python Question

python rename files not working as I expected

I am trying to rename all the files in a directory making multiple changes on each file in order to make files names internet friendly. It works correctly for a few replacements and then it says file not found. I though that if I slowed it down with time.sleep() it would work, but this seems to have no effect (other than being slow). In some cases I can run the script many times and accomplish the goal, but in some cases it completes without error but the changes are not made. Any suggestions would be appreciated.

import os, glob, time
path = os.getcwd()
dirlist = glob.glob('*.pdf')
for filename in dirlist:
os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(' ', '_')))
os.rename(os.path.join(path, filename), os.path.join(path, filename.lower().encode('utf8')))
os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(' (', '-')))
os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(')', '')))
os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(',', '')))
os.rename(os.path.join(path, filename), os.path.join(path, filename.replace('_-_', '-')))

grc grc
Answer

filename.replace() returns a new string - it does not change filename in any way. So filename will become outdated after renaming a file and cause a file not found error next time it is used.

Try something like this:

import os, glob, time

def new_filename(filename):
    return filename.replace(' ', '_').lower().encode('utf8').replace(' (', '-') \
                   .replace(')', '').replace(',', '').replace('_-_', '-')

path  = os.getcwd()
dirlist = glob.glob('*.pdf')
for filename in dirlist:
    os.rename(os.path.join(path, filename), os.path.join(path, new_filename(filename)))