首页 > 解决方案 > 如何将文件夹中的文件复制到多个文件夹中

问题描述

我在文件夹源中有 130 个文件,我想将每个文件复制到单个文件夹 001、002、003 ... 130 中(所有这 130 个文件夹都位于目标文件夹中)。

这样每个文件夹都只包含一个文件。我想出了这个,但可能有点混乱和多余......而且大多数情况下它不起作用。

import shutil
import os

source = '/Users/JohnCN/photo_database/mugshot_frontal/'
files = os.listdir(source)

for i in files:

    for fold in range(1,131):

        if fold<10:
            destination = "/Users/JohnCN/photo_DBsorted/00%s" %fold
            shutil.move(source+i, destination)

        elif fold in range(10,100):
            destination = "/Users/JohnCN/photo_DBsorted/0%s" %fold
            shutil.move(source+i, destination)

        else:
            destination = "/Users/JohnCN/photo_DBsorted/%s" %fold
            shutil.move(source+i, destination)

标签: pythondirectoryshutil

解决方案


我会这样做:

import shutil
import os

source = '/Users/JohnCN/photo_database/mugshot_frontal/'
files = os.listdir(source)

for idx, f in enumerate(files):
    destination = '/Users/JohnCN/photo_DBsorted/{d:03d}'.format(d=(idx + 1))
    shutil.move(source + f, destination)

那么,它有什么作用呢? for idx, f in enumerate(files):在循环时对文件进行计数,因此您知道文件的索引。要获取目的地,idx 用作目录名称。我假设您知道方法format{d:03d}简单地说,分配给 d 的值应该是 3 个字符长,该值是一个整数并且用零填充(例如 003)。当然,此代码假定您没有 1000 多个文件,在这种情况下,只需增加零的数量即可。例如,您可以计算log10文件数的 -value 以获得您必须添加的零的数量。


推荐阅读