Python文件归类迁移练习附如何删除文件或文件夹

目的:
1. 把 jpg,png,gif 文件夹中的所有文件移动到 image 文件夹中,然后删除 jpg,png,gif 文件夹
2. 把 doc,docx,md,ppt 文件夹中的所有文件移动到 document 文件夹中,然后删除


# 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笔记

  1. 删除文件夹一个空文件夹os.rmdir(path)
  2. 删除文件 os.remove(path)
  3. 删除文件夹及其内容shutil.rmtree(path)

猜你喜欢

转载自blog.csdn.net/tmsshikun/article/details/80955140