1

As a beginner in Python I would need your help since I do not know enough how to create such script for my need. To give you an overall idea I have a folder Folder_1 that contains 50 000 different frames from a video in .png :

Folder_1 :
    picture_00001
    picture_00002
    picture_00003
    picture_00004
    ...
    picture_50000

Since my Windows explorer is not running quite well with this huge amount of pictures I will need to move all of them in different folders in order to lower my RAM consumption and letting me working on a batch without considering the 50 000 pictures.

Therefore my objective is to have a script that will simply move the first 500 files to a folder sub_folder1 and then moving the 500 next to sub_folder2 etc... The folders needs to be created with the script as well :

Folder_1
    sub_folder1
         picture_00001
         picture_00002
         ...
         picture_00500

    sub_folder2
         picture_00501
         picture_00502
         ...
         picture_01000

I started working on with for i in range(500) but I have not clue on what to write then.

Hopping this is clear enough otherwise let me know and I will do my best to be even more precised.

Thank you in advance for your help.

4

1 回答 1

3

一种可能的解决方案是:

首先,您找出.png目录中的文件名。您可以通过使用os.listdir(<dir>)返回文件名列表来实现此目的,然后对其进行迭代并选择正确的文件fnmatch

然后你设置增量(在这个例子10中,在你的500),迭代一个生成器range(0, len(files), increment),如果它不存在就创建一个文件夹,然后将文件分块移动。

解决方案:

from fnmatch import fnmatch
import os
import shutil

def get_filenames(root_dir):
    pattern = '*.png'
    files = []
    for file in os.listdir(root_dir):
        if fnmatch(file, pattern):
            files.append(file)
    return files

def distribute_files():
    root_dir = r"C:\frames"
    files = get_filenames(root_dir)
    increment = 10

    for i in range(0, len(files), increment):
        subfolder = "files_{}_{}".format(i + 1, i + increment)
        new_dir = os.path.join(root_dir, subfolder)
        if not os.path.exists(new_dir):
            os.makedirs(new_dir)
        for file in files[i:i + increment]:
            file_path = os.path.join(root_dir, file)
            shutil.move(file_path, new_dir)


if __name__ == "__main__":
    distribute_files()

希望能帮助到你。

问候

于 2019-12-04T18:04:52.150 回答