Renaming OS files by file type in python

Discussion in 'Python' started by blur959, Aug 12, 2010.

  1. blur959

    blur959 Guest

    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
    blur959, Aug 12, 2010
    #1
    1. Advertising

  2. blur959

    MRAB Guest

    blur959 wrote:
    > 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.
    >

    [snip]
    As the traceback says, a file with that new name already exists. You
    can't have 2 files with the same name in the same folder.
    MRAB, Aug 12, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Roy Terrazas

    renaming files using asp

    Roy Terrazas, Jul 30, 2003, in forum: ASP .Net
    Replies:
    1
    Views:
    373
    Craig Deelsnyder
    Jul 30, 2003
  2. master007
    Replies:
    8
    Views:
    831
    Oliver Wong
    Mar 6, 2006
  3. Colin

    Renaming files in C

    Colin, Jul 4, 2003, in forum: C Programming
    Replies:
    3
    Views:
    6,161
    Peter Shaggy Haywood
    Jul 6, 2003
  4. Chris
    Replies:
    6
    Views:
    703
    Chris Uppal
    Mar 6, 2007
  5. Steven D'Aprano
    Replies:
    3
    Views:
    1,824
    Jeffrey Straszheim
    Dec 6, 2008
Loading...

Share This Page