Python实现批量自动整理文件
作者:Python 时间:2023-05-10 21:58:12
为了实现这样的小工具,我们先设想有下面这些功能。
1、可以自定义整理某一个路径下面的所有需要被整理的文件。
2、默认情况下,使用文件后缀作为同一种类文件的文件夹名称,有其他想法的小伙伴可自行扩展。
将使用到的python模块导入到代码块中。
import os # 文件/文件夹应用操作
import shutil # 移动文件
import logging # 使用日志logging来打印日志
选择好需要整理的原始文件目录。
下面是整理完成后的效果图,根据文件类型对各种文件进行整理。
在代码块中加入日志打印的模块,这里日志打印选择的是logging模块。
logger = logging.getLogger('自动归纳文件') # 日志名称
logging.basicConfig(format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') # 日志打印格式
logger.setLevel(logging.DEBUG) # 日志打印级别
下面是文件整理的代码块的全部实现方式,主要部分都加上注释说明。
dir = input('请输入需要整理的文件目录: \n') # 需要整理的文件路径
if os.path.isdir(dir):
logger.info('当前目录[' + dir + ']校验成功!')
paths = []
for file_path, dir_names, file_names in os.walk(r'' + dir):
for file_name in file_names:
try:
file_name_path = os.path.join(file_path, file_name)
dir_ = file_name.split('.')[1]
new_file_name_path = os.path.join(dir, dir_)
# 校验新的文件夹是否已经存在
if os.path.isdir(new_file_name_path):
# 直接移动文件
shutil.move(file_name_path, new_file_name_path)
else:
# 创建好文件夹后移动文件
os.mkdir(new_file_name_path)
shutil.move(file_name_path, new_file_name_path)
paths.append(os.path.join(new_file_name_path, file_name))
except:
logger.error('[' + file_name_path + ']移动发生异常,执行下一个!')
for path in paths:
logger.info('移动完成的文件:' + str(path))
else:
logger.error('输入的文件夹或者目录不存在!')
来源:https://www.cnblogs.com/lwsbc/p/16001709.html
标签:Python,自动,整理,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python数据类型转换汇总
2023-05-13 16:33:00
Vue.js实现微信过渡动画左右切换效果
2023-07-02 17:03:10
![](https://img.aspxhome.com/file/2023/4/139904_0s.gif)
IE6,IE7中定位相关的怪异问题
2009-12-08 12:49:00
![](https://img.aspxhome.com/file/UploadPic/200912/8/position_demo1-45s.png)
Python和Sublime整合过程图示
2023-04-11 15:23:33
![](https://img.aspxhome.com/file/2023/4/98834_0s.png)
Seaborn数据分析NBA球员信息数据集
2021-06-27 03:36:04
![](https://img.aspxhome.com/file/2023/8/94078_0s.png)
浅谈 Webpack 如何处理图片(开发、打包、优化)
2024-06-14 20:48:11
Pytorch 高效使用GPU的操作
2021-10-25 04:45:23
![](https://img.aspxhome.com/file/2023/9/117549_0s.jpg)
Sql server中的char、varchar、text和nchar、nvarchar、ntext的区别
2011-08-14 09:43:44
MySQL数据库远程连接开启方法
2024-01-13 03:39:30
![](https://img.aspxhome.com/file/2023/8/74778_0s.jpg)
SQL Server 2016正式版安装配置过程图文详解
2024-01-26 05:27:15
![](https://img.aspxhome.com/file/2023/8/125678_0s.png)
JavaScript常见数组方法之如何转置矩阵
2024-04-17 10:37:41
![](https://img.aspxhome.com/file/2023/0/136220_0s.png)
如何使用Python 抓取和优化所有网站图像
2022-05-18 12:36:00
![](https://img.aspxhome.com/file/2023/0/77660_0s.png)
kali最新国内更新源sources
2022-03-25 02:53:37
![](https://img.aspxhome.com/file/2023/7/99367_0s.png)
linux下mysql开启远程访问权限 防火墙开放3306端口
2024-01-24 10:59:14
Microsoft VBScript 运行时错误 错误 800a0005 无效的过程调用或参数: chr
2011-03-09 11:03:00
Python的iOS自动化打包实例代码
2022-04-18 01:15:19
![](https://img.aspxhome.com/file/2023/4/95774_0s.jpg)
python可以美化表格数据输出结果的两个工具
2022-06-05 02:33:32
Linux下安装Python3和django并配置mysql作为django默认服务器方法
2023-11-15 01:04:44
javascript编写贪吃蛇游戏
2024-04-22 22:31:00
19个MySQL性能优化要点解析
2024-01-18 16:03:14