【注】:1、学习的过程中发现一个有趣的代码,特来与大家分享。
2、这是将一个指定文件夹下面的所有文件,按文件后缀名,进行归纳整理。
3、这是一个基础的文件夹整理代码,可以按照自己的实际需要来修改代码。
代码实现
import os
# E:\pythonProject\operate\event\dir
path=input('请输入需要整理的文件夹路径:')
all_file=os.listdir(path)
dict={}
# 用字典来实现一个 文件后缀 下面有多个文件
for item in all_file:
name,houzhui=item.split('.')
if houzhui not in dict:
dict[houzhui]=[]
dict[houzhui].append(item)
# 创建后缀名的文件夹、以及挪动文件
for dirname,filelist in dict.items():
if not os.path.exists(path+'\\'+dirname):
os.mkdir(path+'\\'+dirname)
for file in filelist:
old_path=path+'\\'+file
new_path=path+'\\'+dirname+'\\'+file
os.rename(old_path,new_path)
# os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。
if not os.path.isfile(os.getcwd()):
print('整理完成')
效果展示~