Filerenaming loop not functioning
<p>I'm having trouble understanding why my code doesn't work.
I want to rename each file in a particular folder in an order like this:
Foldername_1
Foldername_2 
Foldername_3 
etc...</p>

<p>The code I wrote should increase the 'num' variable by 1 every time it reloops the for loop.</p>

<pre><code>path = os.getcwd()
filenames = os.listdir(path)

    for filename in filenames:
        num = 0
        num = num + 1
        name = "Foldername_{}".format(num)
        os.rename(filename, "{}".format(name))
</code></pre>

<p>However I'm getting this Error:</p>

<blockquote>
  <p>FileExistsError: [WinError 183] Cannot create a file when that file
  already exists: '90' -> 'Foldername_1'</p>
</blockquote>

<p>You are setting <code>num</code> to 0 <em>for each iteration</em>. Move the <code>num = 0</code> <em>out</em> of the loop:</p>

<pre><code>num = 0
for filename in filenames:
    num = num + 1
    name = "Foldername_{}".format(num)
    os.rename(filename, "{}".format(name))
</code></pre>

<p>You don't need to format the <code>name</code> variable again; <code>"{}".format(name)</code> produces the same string as what is already in <code>name</code>. And rather than manually increment a number, you could use the <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code> function</a> to produce the number for you:</p>

<pre><code>for num, filename in enumerate(filenames, 1):
    name = "Foldername_{}".format(num)
    os.rename(filename, name)
</code></pre>

<p>Take into account that <code>os.listdir()</code> doesn't list names in alphabetical order; rather, you'll get an order that is based on the on-disk directory structure, which depends on the order files where created and the exact filesystem implementation. You may want to sort manually:</p>

<pre><code>for num, filename in enumerate(sorted(filenames), 1):
</code></pre>

python python-3.x file-rename