python: rename files based on modified date + iterator
<p>I've got a directory of files that is constantly being added to. Some times there are several files that go in per day, but the number might vary. I'd like to periodically run a script that scans the files and renames them based on the date the file was created + some iterator if there was more than one file for the day. </p>

<p>Here's what I've got so far</p>

<pre><code>#!/usr/bin/python
import os
import datetime
target = "/target_dir"
os.chdir(target)
allfiles = os.listdir(target)
for filename in allfiles:
        if not os.path.isfile(filename):
                continue
        t = os.path.getmtime(filename)
        v= datetime.datetime.fromtimestamp(t)
        x = v.strftime('%Y%m%d')
        loop = 1
        iterator = 1
        temp_name = x + "_" + str(iterator)
        while loop:
                if not os.path.exists(temp_name + '.mp4'):
                        os.rename(filename, temp_name + '.mp4')
                        loop = 0
                else:
                        temp_name = x + '_' + str(iterator)
                        iterator+=1
</code></pre>

<p>And that seems to work but if I run the script a second time it changes the filenames prematurely (i.e. date1-1.mp4 becomes date1-2.mp4, etc)</p>

<p>Any suggestions? </p>
