python 实现根据文件名自动分类移动至不同的文件夹

目录下很多word文档需要单独创建文件整理

  • 第一步:梳理出待整理目录下文件的名称
  • 第二步:利用for循环遍历,去掉文件后缀,根据文档文件名创建新文件夹名
  • 第三步:将文件移动至对应的文件夹里

完整代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#脚本放到源文件同目录下,用法:python3 xxx.py

#脚本功能:根据文件名自动创建文件夹且将文件移动到对应的文件夹里
import os as os
import shutil as shutil

def main():
        # 源文件存储位置
        path = "."
        try:
                filelist = os.listdir(path)
                print("当前目录下的文件:",filelist)
                for file in filelist:
                        # print(file)
                        newfile = file.replace(".doc", "").replace(" ", "").replace("x", "")
                        #print(newfile)
                        if ".py" not in file:
                                os.mkdir(newfile)
                                print(newfile+"  创建成功")
                                try:
                                        shutil.move(file, "./" + file.replace(".doc", "").replace("x", ""))
                                        print(file+"  转移成功")
                                except Exception as e:
                                        print(file+"  转移失败")
                print(">>>>>>>>>>>>>>>>>>>转移完毕<<<<<<<<<<<<<<<<<<<<<")

        except Exception as e:
                print(">>>>>>>>>>>>>>>>>>>Error,文件夹已存在!!!<<<<<<<<<<<<<<<<<<<<<")


if __name__ == "__main__":
        main()
posted @ 2021-07-09 17:29  g7y12  阅读(2590)  评论(0编辑  收藏  举报