目的:
- 把 jpg,png,gif 文件夹中的所有文件移动到 image 文件夹中,然后删除 jpg,png,gif 文件夹
- 把 doc,docx,md,ppt 文件夹中的所有文件移动到 document 文件夹中,然后删除1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 # coding:utf-8
 import os
 import shutil
 path = "/Users/sk/Documents/problem2_files3"
 image = ["jpg", "png", "gif"]
 document = ["doc", "docx", "md", "ppt"]
 dic_list = os.listdir(path)
 # 创建目标文件夹,注意先判断是否存在,如果存在,但是程序没有提前判断,会导致报错
 if not os.path.exists(path+"/image"):
 os.makedirs(path+"/image")
 if not os.path.exists(path+"/document"):
 os.makedirs(path+"/document")
 # 遍历各个文件夹
 for d in dic_list:
 if d in image:
 d_list = os.listdir(path+"/"+d)
 for d_l in d_list:
 # 移动文件
 shutil.move(path+'/'+d+"/"+d_l, path+"/image")
 # 删除原来的文件夹
 os.rmdir(path+"/"+d)
 elif d in document:
 d_list = os.listdir(path+"/"+d)
 for d_l in d_list:
 shutil.move(path+"/"+d+"/"+d_l, path+"/document")
 os.rmdir(path + "/" + d)
Python笔记
- 删除文件夹一个空文件夹os.rmdir(path)
- 删除文件 os.remove(path)
- 删除文件夹及其内容shutil.rmtree(path)
