python - 如何将文件夹中的文件复制到多个文件夹中
问题描述
我在文件夹源中有 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)
解决方案
我会这样做:
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 以获得您必须添加的零的数量。
推荐阅读
- python - 如何解决python中数据透视表的错误
- javascript - JavaScript - 减少数组和 groupBy
- python - 不接收使用 python 套接字从服务器返回的消息
- javascript - 如何在 redux-observable 史诗中链接 RxJS 可观察?
- javascript - 网络摄像头到 BlobURL 以进行视频播放
- sql - MySql 附近搜索
- python - 熊猫按不规则日期范围分组
- flutter - Flutter & Geocoder & Geolocator : 如何获取英文国家名称?
- pytorch - PyTorch:type(a)、a.type、a.type() 之间的区别
- python - 使用 webpack-quasar 在 Django 服务器中共享静态文件