I am simply trying to write a python script that will change the filename in a directory of files
<p>I am trying to create a script in python 2.7 that will rename all the files in a directory. Below is the code I have so far. The first function removes any numbers in the file name. The second function is supposed to rename the new file name. I get the following error when the second function runs:</p>

<blockquote>
  <p>[Error 183] Cannot create a file when that file already exists</p>
</blockquote>

<p>I know this is because I am not looping through the files and adding an incrementing number to the new filename, so the script changes the name of the first file, and then tries to change the name of the second file to the same name as the first, producing the error. </p>

<p>Can someone help me create a loop that adds an incrementing number to each filename in the directory?</p>

<p>I tried adding:</p>

<pre><code>if file_name == filename:
file_name = file_name + 1
</code></pre>

<p>in the while loop, but that obviously doesn't work because I cant concatenate an integer with a string.</p>

<pre><code>import os
def replace_num():
    file_list = os.listdir(r"C:\Users\Admin\Desktop\Python Pics")
    print(file_list)
    saved_path = os.getcwd()
    print("Current Working Directory is " + saved_path)
    os.chdir(r"C:\Users\Admin\Desktop\Python Pics")
    for file_name in file_list:
        print("Old Name - " + file_name)
        os.rename(file_name, file_name.translate(None, "0123456789"))
    os.chdir(saved_path)
replace_num()

def rename_files():
    file_list = os.listdir(r"C:\Users\Admin\Desktop\Python Pics")
    print(file_list)
    saved_path = os.getcwd()
    print("Current Working Directory is " + saved_path)
    os.chdir(r"C:\Users\Admin\Desktop\Python Pics")
    for new_name in file_list:
        print("New Name - " + new_name)
        try:
            os.rename(new_name, "iPhone")
        except Exception, e:
            print e
rename_files()
</code></pre>

<p>instead of doing:</p>

<pre><code>if file_name == filename:
    file_name = file_name + 1
</code></pre>

<p>do something like this:</p>

<pre><code>counter = 0
for file_name in file_container:
    if file_name == file_name: # this will always be True - so it's unnecessary
        file_name = "{0}_{1}".format(file_name, counter)
        counter += 1
</code></pre>

python python-2.7 loops increment