代码存在可以改进的地方,但是不妨碍实现分离格式的目的。
import os
import os.path
import shutil
#创建各种格式文件夹
def create_files(path):
format_set=[] # 定义一个空列表
obj_list=os.listdir(path) # 穷举文件
for obj in obj_list:
format=os.path.splitext(obj)[1] # 该函数可以得出当前对象的格式
if format not in format_set: # 未出现在列表当中的就往列表里添加
format_set.append(format) # 添加
new_dir=path+'/'+format[1:] # 路径
try:
os.mkdir(new_dir) # 创建
except FileExistsError:
print('%s文件已存在,无需创建该文件'%format)
return obj_list,format_set
#对目前数据按格式分类,并分配到对应格式文件中
def allocate_file(path):
obj_list,format_set=create_files(path) # 将创建文件函数的返回对象进行赋值
for obj in obj_list:
name=os.path.splitext(obj)[0] # 取名
format=os.path.splitext(obj)[1] # 取格式
dst=path+'/'+format[1:] # 目标文件目录
try:
src=path+'/'+name+format # 需要修改的文件
shutil.move(src,dst) # 移动到dst中,自行了解该函数意义
except:
continue
allocate_file('F:/objs/results/views')