vanoccupanther vanoccupanther - 3 months ago 12
Python Question

Python: moving file to a newly created directory

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.

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.

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

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.

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/')

Answer

A simple fix would be to check if '*_01.png' is in the file name i and change the shutil.move to include i, the filename. (It's also worth mentioning that iis not a good name for a filepath

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

Additionally is [there some way] 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.

You could create file names doing something as simple as this:

for i in range(10):
    #simple string parsing
    file_name = 'sub_frame_'+str(i)
    folder_name = 'folder_sub_frame_'+str(i)
Comments