python将多个文件按顺序拆分到文件夹
最近整理照片,需要将大量照片按名称分成小文件夹,csdn上有大神 法毅的博客 给出程序:
#!coding=utf-8
import os
import shutil
file_path = '/Users/user/Downloads' #原文件存放地址
num = 80 #每个文件夹存放的个数
list_ = os.listdir(file_path)
list_.sort() #按名称排序
if num > len(list_):
print('num长度需小于:', len(list_))
exit()
if int(len(list_) % num) == 0:
num_file = int(len(list_) / num)
else:
num_file = int(len(list_) / num) + 1
cnt = 0
for n in range(1, num_file + 1): # 创建文件夹,名称加序号
new_file = os.path.join(file_path + str(n))
if os.path.exists(new_file + str(cnt)):
print('该路径已存在,请解决冲突', new_file)
exit()
print('创建文件夹:', new_file)
os.mkdir(new_file)
list_n = list_[num * cnt:num * (cnt + 1)]
for m in list_n:
old_path = os.path.join(file_path, m)
new_path = os.path.join(new_file, m)
shutil.copy(old_path, new_path)
cnt += 1