Python: moving file to a newly created directory
<p>I've got my script creating a bunch of files (size varies depending on inputs) and I want to be certain files in certain folders based on the filenames.</p>

<p>So far I've got the following but although directories are being created no files are being moved, I'm not sure if the logic in the final for loop makes any sense.</p>

<p>In the below code I'm trying to move all .png files ending in _01 into the sub_frame_0 folder.</p>

<p>Additionally is their someway to increment both the file endings _01 to _02 etc., and the destn folder ie. from sub_frame_0 to sub_frame_1 to sub_frame_2 and so on.</p>

<pre><code>for index, i in enumerate(range(num_sub_frames+10)):
    path = os.makedirs('./sub_frame_{}'.format(index))

# Slice layers into sub-frames and add to appropriate directory

list_of_files = glob.glob('*.tif')
for fname in list_of_files: 
    image_slicer.slice(fname, num_sub_frames) # Slices the .tif frames into .png sub-frames

list_of_sub_frames = glob.glob('*.png')
for i in list_of_sub_frames:
    if i == '*_01.png':
        shutil.move(os.path.join(os.getcwd(), '*_01.png'), './sub_frame_0/')
</code></pre>

<p>Here is a complete example using regular expressions. This also implements the incrementing of file names/destination folders</p>

<pre><code>import os
import glob
import shutil
import re

num_sub_frames = 3
# No need to enumerate range list without start or step
for index in range(num_sub_frames+10):
    path = os.makedirs('./sub_frame_{0:02}'.format(index))

# Slice layers into sub-frames and add to appropriate directory

list_of_files = glob.glob('*.tif')
for fname in list_of_files:
    image_slicer.slice(fname, num_sub_frames) # Slices the .tif frames into .png sub-frames

list_of_sub_frames = glob.glob('*.png')
for name in list_of_sub_frames:
    m = re.search('(?P&lt;fname&gt;.+?)_(?P&lt;num&gt;\d+).png', name)
    if m:
        num = int(m.group('num'))+1
        newname = '{0}_{1:02}.png'.format(m.group('fname'), num)
        newpath = os.path.join('./sub_frame_{0:02}/'.format(num), newname)
        print m.group() + ' -&gt; ' + newpath
        shutil.move(os.path.join(os.getcwd(), m.group()), newpath)
</code></pre>

python filesystems shutil