Renaming OS files by file type in python

blur959 blur959 at hotmail.com
Thu Aug 12 15:15:23 CEST 2010


Hi all, I am creating a program that renames all files of the similar
file type. But i am stuck at this part. I tried running this code and
I got this error:    new_name = os.rename(path, newpath)
WindowsError: [Error 183] Cannot create a file when that file already
exists. Hope you guys could help.



import os

directory = raw_input("Please input file directory. \n\n")

s = raw_input("Please input a name to replace. \n\n")
ext = raw_input("input file ext")

for filename in listdir(directory):
    if ext in filename:
        path = join(directory, filename)
        fnpart = os.path.splitext(filename)[0]
        replace_name = filename.replace(fnpart, s)
        newpath = os.path.join(directory, replace_name)

        new_name = os.rename(path, newpath)
        print new_name




More information about the Python-list mailing list