Python办公自动化|自动整理文件,一键完成!

Python办公自动化|自动整理文件,一键完成!(1) 由于我们是利用后缀名建立文件夹,所以索性将文件名中没有.的 文件 类型统一分类到others文件夹了,(这个实现逻辑大致上没有问题,但是依然忽略了一种极端情况:有些文件没有后缀名,且文件名中有个.,哈哈哈哈这种就会被上面的实现逻辑拆解出错误的后缀名了。为了避免移动文件夹而造成的异常,尤其是系统盘,因此这里用的是复制。当我学到一定基础,有自己的理解能力的时候,会去阅读一些前辈整理的书籍或者手写的笔记资料,这些笔记详细记载了他们对一些技术点的理解,这些理解是比较独到,可以学到不一样的思路。 阅读详情

前言

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理。

PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取

python免费学习资料、代码以及交流解答点击即可加入


大家好,又到了Python办公自动化专题

本文跟大家分享一个文件整理脚本的实现过程。具体的功能很简单,给定一个打算整理的文件夹目录,这个脚本可以将该目录下的所有文件都揪出来,并且根据后缀名归类到不同的文件夹里,就像下图一样,简直是整理爱好者的福音


通过本例还可以学到:os、glob、shutil三个标准库的综合运用,现在让我们一起来捋一捋实现的逻辑。

 

首先是导入需要的库

import os
import shutil
import glob

os库可以完成操作系统层面大量操作,例如文件夹的创建、移动、重命名、删除等,有些功能实现的不是很完美,就用到shutil库跟其互补了,例如文件的复制、移动等。glob库可以利用通配符进行文件的搜索获取,非常强大

# 设置建立分类总文件夹的路径,这里按自己的实际路径修改
mkdir_path = r'C:\Users\chenx\文件夹分类'
# 设置需要遍历整理的文件夹路径,可以依据自己的实际需求修改
goal_dir = r'C:\xxxxxxxx)'

if not os.path.exists(mkdir_path):
    os.mkdir(mkdir_path)

os.mkdir可以在指定路径创建文件夹,但如果文件夹已经存在则会报错,因此谨慎一点可以利用os.path.exists先对文件夹的存在与否进行判断,接下来是代码核心循环,为了方便理解先简化成如下形式:

for file in glob.glob(f'{goal_dir}/**/*', recursive=True):
    if os.path.isfile(file):
        print(file)

glob.glob(f'{goal_dir}/ * * / * ', recursive=True)中/是通配符的重要用法,可以代表任意个字符,包括0个字符,recursive参数的设置确保遍历。由于需要找出所有的文件而非文件夹,这里用os.path.isfile进行判断。最后可以输出文件的绝对路径先看看代码有没出现错误,让我们继续往下写

for file in glob.glob(f'{goal_dir}/**/*', recursive=True):
    if os.path.isfile(file):
        filename = os.path.basename(file)
        if '.' in filename:
            suffix = filename.split('.')[-1]
        else:
            suffix = 'others'

这里发生了什么呢?确认遍历到的是文件后,先用os.path.basename获取绝对路径中的文件名,接下来就是获取后缀名了。可以简单用split根据.将字符串“劈开”,然后取最后一个元素就是后缀名了,但注意这里必须要考虑一个特殊情况:有些文件没有后缀名(文件类型就叫 文件),且名字中也没有.,这时用字符串方法split就会报错。如下图:


因此需要先判断文件中有没有.。由于我们是利用后缀名建立文件夹,所以索性将文件名中没有.的 文件 类型统一分类到others文件夹了,(这个实现逻辑大致上没有问题,但是依然忽略了一种极端情况:有些文件没有后缀名,且文件名中有个.,哈哈哈哈这种就会被上面的实现逻辑拆解出错误的后缀名了。更好的方法是有个函数可以直接获取文件的后缀名,利用这个对文件进行分类,感兴趣的读者可以自己尝试),接下来就可以根据后缀名产生文件夹了,这里依然要注意先判断文件夹是否已经产生

 

for file in glob.glob(f'{goal_dir}/**/*', recursive=True):
    if os.path.isfile(file):
        filename = os.path.basename(file)
        if '.' in filename:
            suffix = filename.split('.')[-1]
        else:
            suffix = 'others'
        if not os.path.exists(f'{mkdir_path}/{suffix}'):
            os.mkdir(f'{mkdir_path}/{suffix}')
        shutil.copy(file, f'{mkdir_path}/{suffix}')

为了避免移动文件夹而造成的异常,尤其是系统盘,因此这里用的是复制。按照需要也可以换成shutil.move最后我们可以加上分类文件夹和所有文件的计数并输出。完整代码如下,拿走就能用!

import os
import shutil
import glob

mkdir_path = r'C:\Users\chenx\文件夹分类'
goal_dir = r'C:\xxxxxxxx'

if not os.path.exists(mkdir_path):
    os.mkdir(mkdir_path)

file_num = 0
dir_num = 0

for file in glob.glob(f'{goal_dir}/**/*', recursive=True):
    if os.path.isfile(file):
        filename = os.path.basename(file)
        if '.' in filename:
            suffix = filename.split('.')[-1]
        else:
            suffix = 'others'
        if not os.path.exists(f'{mkdir_path}/{suffix}'):
            os.mkdir(f'{mkdir_path}/{suffix}')
            dir_num += 1
        shutil.copy(file, f'{mkdir_path}/{suffix}')
        file_num += 1

print(f'整理完成,有{file_num}个文件分类到了{dir_num}个文件夹中')
python程序实现文件自动分类 python程序实现某一文件夹内不同文件类型自动分类,输入excel表格中 立即下载

相关推荐

python实现自动清理重复文件

前言 大家好,又到了Python办公自动化系列。 今天分享一个系统层面的自动化案例: 「给定一个文件夹,使用Python检查给定文件夹下有无文件重复,若存在重复则删除」 主要涉及的知识点有: os模块综合应用 glob模块综合应用 利用filecmp模块比较两个文件 步骤分析 该程序实现的逻辑可以具化为: 遍历获取给定文件夹下的所有文件,然后通过嵌套循环两两比较文件是否相同,如果相同则删除后者。 实现问题的关键就变成了? 如何判断两个文件是否相同? 在这里我们可以使用filecmp模块,来看看官方的介绍文档: filecmp.cmp(f1, f2, shallow=True

[Python模块学习] glob模块

Python glob模块学习笔记

GanZiQim的技术备忘录 2万+

ClickHouse的bitmap使用

ClickHouse的bitmap使用 bitmap的基本使用 在CK中bitmap有两种构建方式,在ClickHouse的官网有说明: (1)一个是由聚合函数groupBitmapState构造的, (2)另一个是由Array Object构造的。同时还可以将位图对象转化为数组对象。 bitmap实战 数据和基本数据表准备 创建一张基本表,一个用户表,有多个描述的维度,每个维度由该维度的唯一id。 CREATE TABLE test02(id UInt16, tag1 UInt8, tag2 UInt8,

zg_hover的专栏 5655

超级好用的Python模块——glob模块

除了上面提到的三个通配符,在glob模块的3.5版本中,又新增了一个通配符**,它主要与参数recursive搭配使用。参数recursive代表递归调用,其默认为False,当其值为True时,表示递归调用。glob模块可以查找符合特定规则的文件/文件夹,并将搜索到的结果返回到一个列表中。‘案例[2]‘表示我们要找到以“案例”开头,并且后面茎根一个字符必须是数字2。'表示我们要找以“案例”开头,并且后面紧跟一个字符的文件。'*案例*'表示我们要找到文件名称中包含“文件夹”三个字的文件。

Bruce_xiaowei的博客 824

APS生产排程系统——ERP、MES、APS系统的关联和区别

APS生产排程系统——ERP、MES、APS系统的关联和区别

这里有一只小马吖 2万+

Linux内核支持串口屏,linux串口触摸屏设计总结

Linux serial touch 设计总结概述:最近在做嵌入式linux下串口触摸屏设计,遇到一些问题,经过查找资料和请教同事,总算把问题解决了,事后有把linux相关的内核代码仔细看了一遍,为了有点成果,特别写了个总结。如有任何问题请联系yxj_5421@http://www.doczj.com/doc/87b94b1e227916888486d76d.html,转载请标明出处。系统资源:L...

weixin_39935903的博客 1297

glob模块使用

详解glob模块

正在挣扎中的人 684

机器学习篇-KNN算法实现鸢尾花模型和手写数字识别模型

一个样本最相似的k个样本中的大多数属于某一个类别, 则该样本也属于这个类别类似于: 近朱者赤近墨者黑回归机器建模流程:数据获取数据基本处理(空值和非法值)特征工程(特征提取, 特征预处理(归一化, 标准化), 特征降维, 特征选择, 特征组合)模型训练模型预测模型评估# 1. 定义函数 dm01_load_iris(), 用于加载 鸢尾花数据集, 并简单查看下数据集的各部分.# 1. 加载数据集.​# 2. 打印iris_data, 发现其实是1个: 字典.​。

m0_60916732的博客 2408

Python办公自动化|自动整理文件,一键完成

大家好,又到了Python办公自动化专题本文跟大家分享一个文件整理脚本的实现过程。具体的功能很简单,给定一个打算整理的文件夹目录,这个脚本可以将该目录下的都揪出来,并且里,就像下图一样,简直是整理爱好者的福音osglobshutil三个标准库的综合运用,现在让我们一起来捋一捋实现的逻辑。首先是导入需要的库库可以完成操作系统层面大量操作,例如文件夹的等,有些功能实现的不是很完美,就用到shutil库跟其互补了,例如文件的等。glob库可以利用通配符进行获取,非常强大。

Python栈_基的博客 526

验证(uvm常见问题)--子类和父类的句柄和对象问题

sv中的子类和父类 在sv中,有如下两个类,child继承于parent。然后在test module中,正确转换的方法如下面所示。其中c1,c2,p1 都指向了同一个子类的对象c1。总结如下: 一个子类的对象是包括子类的成员变量,方法和父类的成员变量,方法。 子类的句柄c1可以直接赋值给父类的句柄p1,此时p1只可以访问父类的成员变量和方法,或者子类的虚方法,比如下面调用p1.display是...

q876507447的博客 7634

本地如何安装midscene.js运行环境

手把手教你本地安装midscene.js运行环境

实践助梦想成长 2611

如何通过Python自动整理文件?

哈喽,大家好,今天给大家介绍一下,如何通过Python自动整理文件。

编辑编辑器 1759

向量库深度解析:选型、索引原理与生产实践

本文系统解析五大主流向量库(pgvector、Milvus、Weaviate、ChromaDB、Faiss)的定位、优缺点与适用场景,深入拆解FLAT、IVF、HNSW等核心索引原理,并重点分析Milvus的Compaction机制。针对数据治理场景,提供精准选型建议:中小规模优先pgvector或Weaviate,超大规模选择Milvus,开发测试推荐ChromaDB。核心索引推荐HNSW,兼顾检索速度与召回率。全文从理论到实践,为开发者提供清晰的向量库选型逻辑与生产落地指南。

a123147abc的博客 364

Python办公自动化,自动整理文件,一键完成!神器!

大家好,又到了Python办公自动化专题 本文跟大家分享一个文件整理脚本的实现过程。具体的功能很简单,给定一个打算整理的文件夹目录,这个脚本可以将该目录下的所有文件都揪出来,并且根据后缀名归类到不同的文件夹里,就像下图一样,简直是整理爱好者的福音 通过本例还可以学到:os、glob、shutil三个标准库的综合运用,现在让我们一起来捋一捋实现的逻辑。 首先是导入需要的库 importos importshutil importglob os库可以完成操作系统层面大...

爬遍所有网站 451

码农新宠大对决:GitHub Copilot、通义灵码和CodeLlama谁主沉浮?

本文对三款主流AI编程工具GitHub Copilot、通义灵码和CodeLlama进行了全面对比分析。GitHub Copilot在多语言支持和代码质量上表现突出;通义灵码在中文理解和阿里云生态集成方面优势明显;CodeLlama则以开源可定制见长。文章从代码生成、理解能力、多语言支持、使用体验等维度展开评测,并结合实际案例说明不同开发者群体的适用选择。建议新手可优先考虑通义灵码,经验开发者适合GitHub Copilot,而有定制需求的企业团队则可选择CodeLlama。随着AI技术发展,这些工具将持续

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 676

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Python 办公自动化|自动整理文件,一键完成!

本文跟大家分享一个文件整理脚本的实现过程。具体的功能很简单,给定一个打算整理的文件夹目录,这个脚本可以将该目录下的所有文件都揪出来,并且根据后缀名归类到不同的文件夹里,就像下图一样,简直是整理爱好者的福音

DEVELOPERAA的博客 257

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 用Python打造一款文件搜索工具,所有功能自己定义!
下一篇: 老板让我从几百个Excel中查找数据,我用Python一分钟搞定!
酸菜鱼编程
博客等级 码龄6年 155粉丝 63原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值