python实现自动整理文件
作者:多好一次 发布时间:2021-03-04 14:15:46
标签:python,自动,整理,文件
前言:
平时工作没有养成分类的习惯,整个桌面杂乱无章都是文档和资料,几乎快占满整个屏幕了。所以必须要整理一下了,今天我们来看下用python如何批量将不同后缀的文件移动到同一文件夹。
演示效果:
使用前
使用后
代码:
# # -*- coding:utf-8 -*-
import os
import glob
import shutil
import tkinter
import tkinter.filedialog
from datetime import datetime
def start():
? ? root = tkinter.Tk()
? ? root.withdraw()
? ? dirname = tkinter.filedialog.askdirectory(parent=root,initialdir="/",title='请选择文件夹')
? ? return dirname
# 定义一个文件字典,不同的文件类型,属于不同的文件夹
file_dict = {
? ? "图片": ["jpeg", "jpg", "tiff", "gif", "bmp", "png", "bpg", "svg", "heif", "psd"],
? ? "视频": ["avi", "flv", "wmv", "mov", "mp4", "webm", "vob", "mng", "qt", "mpg", "mpeg", "3gp", "mkv"],
? ? "音频": ["aac", "aa", "aac", "dvf", "m4a", "m4b", "m4p", "mp3", "msv", "ogg", "oga", "raw", "vox", "wav", "wma"],
? ? "文档": ["oxps", "epub", "pages", "docx", "doc", "fdf", "ods", "odt", "pwi", "xsn", "xps", "dotx", "docm", "dox",
"rvg", "rtf", "rtfd", "wpd", "xls", "xlsx","xlsm","ppt", "pptx", "csv", "pdf", "md","xmind"],
? ? "压缩文件": ["a", "ar", "cpio", "iso", "tar", "gz", "rz", "7z", "dmg", "rar", "xar", "zip"],
? ? "文本": ["txt", "in", "out","json","xml","log"],
? ? "程序脚本": ["py", "html5", "html", "htm", "xhtml", "cpp", "java", "css","sql"],?
? ? '可执行程序': ['exe', 'bat', 'lnk', 'sys', 'com','apk'],
? ? '字体文件': ['eot', 'otf', 'fon', 'font', 'ttf', 'ttc', 'woff', 'woff2','shx'],
? ? '工程图文件':['bak','dwg','dxf','dwl','dwl2','stp','SLDPRT','ipj','ipt','idw']
}
# 定义一个函数,传入每个文件对应的后缀。判断文件是否存在于字典file_dict中;
# 如果存在,返回对应的文件夹名;如果不存在,将该文件夹命名为"未知分类";
def JudgeFile(suffix):
? ? for name, type_list in file_dict.items():
? ? ? ? if suffix.lower() in type_list:
? ? ? ? ? ? return name
? ? return "未知分类"
if __name__ == '__main__':
? ? try:
? ? ? ? while True:
? ? ? ? ? ? path = start()
? ? ? ? ? ? print("---->路径是: ",path)
? ? ? ? ? ? if path == "":
? ? ? ? ? ? ? ? print("没有选择路径!")
? ? ? ? ? ? ? ? break
? ? ? ? ? ? # 递归获取 "待处理文件路径" 下的所有文件和文件夹。
? ? ? ? ? ? startTime = datetime.now().second
? ? ? ? ? ? for file in glob.glob(f"{path}/**/*", recursive=True):
? ? ? ? ? ? ? ? # 由于我们是对文件分类,这里需要挑选出文件来。
? ? ? ? ? ? ? ? if os.path.isfile(file):
? ? ? ? ? ? ? ? ? ? # 由于isfile()函数,获取的是每个文件的全路径。这里再调用basename()函数,直接获取文件名;
? ? ? ? ? ? ? ? ? ? file_name = os.path.basename(file)
? ? ? ? ? ? ? ? ? ? suffix = file_name.split(".")[-1]
? ? ? ? ? ? ? ? ? ? # 判断 "文件名" 是否在字典中。
? ? ? ? ? ? ? ? ? ? name = JudgeFile(suffix)
? ? ? ? ? ? ? ? ? ? # 根据每个文件分类,创建各自对应的文件夹。
? ? ? ? ? ? ? ? ? ? if not os.path.exists(f"{path}\\{name}"):
? ? ? ? ? ? ? ? ? ? ? ? os.mkdir(f"{path}\\{name}")
? ? ? ? ? ? ? ? ? ? ? ? print('path-->',name)
? ? ? ? ? ? ? ? ? ? # 将文件复制到各自对应的文件夹中。
? ? ? ? ? ? ? ? ? ? # shutil.copy(file, f"{path}\\{name}")
? ? ? ? ? ? ? ? ? ? # 将文件移动到各自对应的文件夹中。
? ? ? ? ? ? ? ? ? ? shutil.move(file, f"{path}\\{name}")
? ? ? ? ? ? endTime = datetime.now().second
? ? ? ? ? ? countTime= endTime-startTime
? ? ? ? ? ? print("---->已经整理完成。共花费 {} s".format(countTime))
? ? ? ? ? ? a = input('---->请按回车键退出:')
? ? ? ? ? ? if a == '':
? ? ? ? ? ? ? ? break
? ? except BaseException:
? ? ? ? print('存在重复的文件!')
执行起来很简单,只要写完程序,点击程运行,等待弹出窗口,选择需要整理的文件夹即可。
如果觉得以上代码觉得复杂,可以尝试以下更为简单的程序。
如何实现文件自动分类?
同一目录下存在很多不同类型的资源条件
1 .分类
2.创建分类目录
3.移动文件资源
import os
import shutil
import tkinter
import tkinter.filedialog
from datetime import datetime
def start():
? ? root = tkinter.Tk()
? ? root.withdraw()
? ? dirname = tkinter.filedialog.askdirectory(parent=root,initialdir="/",title='请选择文件夹')
? ? return dirname
# 源文件存在路径
src_dir=start()
# 分类资源存在路径
dest_dir=src_dir
# 判断目录是否存在
if not os.path.exists(dest_dir):
? ? os.mkdir(dest_dir)
# 源目录分析
files=os.listdir(src_dir)
for item in files:
? ? src_path=os.path.join(src_dir,item)
? ? # 判断状态
? ? if os.path.isfile(src_path):
? ? ? ? #如果是文件,进入代码块
? ? ? ? # 判断文件资源的类型
? ? ? ? ndir = item.split('.')[-1]
? ? ? ? desc_path=os.path.join(dest_dir,ndir)
? ? ? ? # 创建分类目录
? ? ? ? if not os.path.exists(desc_path):
? ? ? ? ? ? # 如果分类子目录不存在,创建
? ? ? ? ? ? os.mkdir(desc_path)
? ? ? ? shutil.move(src_path,desc_path)
来源:https://blog.csdn.net/weixin_42750611/article/details/124051648


猜你喜欢
- 本文实例讲述了Python变量、数据类型、数据类型转换相关函数用法。分享给大家供大家参考,具体如下:python变量的使用不需要进行类型声明
- 一、实验目的实现学生选课系统二、实验环境Python3.6pymysql(Python连接MySQL)xlrd(操作Excel)三、程序结构
- 我就废话不多说了,直接上代码吧:package mainimport ("flag""fmt"&qu
- 拼接字符串使用“+”可以对多个字符串进行拼接语法格式: str1 + str2>>> str1 = "aaa&q
- 本文主要给大家介绍的是关于Golang解析json数据的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍:使用 Gol
- 本文实例讲述了Python redis操作。分享给大家供大家参考,具体如下:一、redisredis是一个key-value存储系统。和Me
- 本文介绍了Python3网络爬虫之使用User Agent和 * 隐藏身份,分享给大家,具体如下:运行平台:WindowsPython版本
- 删除文件os.remove( filename ) # filename: "要删
- 在这种配置下我们要实现关键词不区分大小写搜索并高亮显示要借助ASP的正则处理了,请看下面代码:<% Function&nbs
- 本文实例讲述了mysql中left join设置条件在on与where时的用法区别。分享给大家供大家参考,具体如下:一、首先我们准备两张表来
- 除了使用pycharm外,还可使用vscode来操作pyqt,方法如下:1. 在vscode中配置相关的pyqt的相关根据自己实际情况修改第
- php mysql PDO 查询操作的实例详解<?php $dbh = new PDO('mysql:host=localho
- 下面先来看看例子:table表字段1 字段2 i
- 机器学习可应用在各个方面,本篇将在系统性进入机器学习方向前,初步认识机器学习,利用线性回归预测波士顿房价;原理简介利用线性回归最简单的形式预
- 一,如何检测和转换接口变量的类型在Go语言的interface中可以是任何类型,所以Go给出了类型断言来判断某一时刻接口中所含有的类型,例如
- 一、UNION和UNION ALL的作用和语法UNION 用于合并两个或多个 SELECT 语句的结果集,并消去表中任何重复行。UNION
- 一、假设有这样一个原始dataframe二、提取索引(已经做了一些操作将Age为NaN的行提取出来并合并为一个dataframe,这里提取的
- 什么是 Socket?Socket又称"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网
- ./runInstaller 启动图形化报错 PRVF-0002 : Could not retrieve local nodename.
- 一、根据vux文档直接安装,无需手动配置npm install vue-cli -g // 如果还没安装vue init ai