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>As you said, the logic of the final loop does not make sense.</p>

<pre><code>if i == '*_01.ng'
</code></pre>

<p>It would evaluate something like <code>'image_01.png' == '*_01.png'</code> and be always false.</p>

<p>Regexp should be the way to go, but for this simple case you just can slice the number from the file name.</p>

<pre><code>for i in list_of_sub_frames:
    frame = int(i[-6:-4]) - 1
    shutil.move(os.path.join(os.getcwd(), i), './sub_frame_{}/'.format(frame))
</code></pre>

<p>If <code>i = 'image_01.png'</code> then <code>i[-6:-4]</code> would take '01', convert it to integer and then just subtract 1 to follow your schema.</p>

python filesystems shutil