网络编程
位置:首页>> 网络编程>> Python编程>> 基于Python实现文件分类器的示例代码

基于Python实现文件分类器的示例代码

作者:Sir?老王  发布时间:2023-06-02 12:49:10 

标签:Python,文件,分类

本文实现文件分类器的目的主要是为了将办公过程中产生的各种格式的文件完成整理。

通过自定义需要整理的文件目录,将该目录下面的全部文件按照文件格式完成分类操作。

基于Python实现文件分类器的示例代码

实现逻辑使用的python技术栈就是os、glob、shutil三个标准库的综合运用,完成自动化的文件整理。

分别将这三个文件处理模块导入代码块中,进入后续的开发操作。

# It imports the os module.
import os

# Shutil is a module that provides a number of high-level operations on files and collections of files.
import shutil

# The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell,
# although results are returned in arbitrary order. No tilde expansion is done, but *, ?, and character ranges expressed
# with [] will be correctly matched.
import glob
import sys

将需要分类的文件目录uncatched_dir以及分类后文件存放目录target_dir设置为可以手动输入的方式。

# Asking the user to input the path of the directory that contains the files to be sorted.
uncatched_dir = input('请输入待分类的文件路径:\n')

# It checks if the uncatched_dir is empty.
if uncatched_dir.strip() == '':
    print('待分类的文件夹路径不能为空!')
    sys.exit()

# Asking the user to input the path of the directory that contains the files to be sorted.
target_dir = input('请输入分类后文件存放的目标路径:\n')

# It checks if the target_dir is empty.
if target_dir.strip() == '':
    print('分类后的文件存放路径不能为空!')
    sys.exit()

基于Python实现文件分类器的示例代码

检验输入的分类后文件存放目录路径是否存在,因为很可能是输入一个新的路径,不存在时则新建一个该路径。

# It checks if the target_dir exists. If it does not exist, it creates a new directory in the current working directory.
if not os.path.exists(target_dir):
    # It creates a new directory in the current working directory.
    os.mkdir(target_dir)

定义一个文件移动数量的变量file_move_num,以及一个新建的文件夹数量的变量dir_new_num用于记录文件整理的结果记录。

# A variable that is used to count the number of files that have been moved.
file_move_num = 0

# A variable that is used to count the number of new directories that have been created.
dir_new_num = 0

遍历需要整理的文件夹目录uncatched_dir,对该目录下面的所有类型的文件进行自动整理操作。

# A for loop that iterates through all the files in the uncatched_dir directory.
for file_ in glob.glob(f'{uncatched_dir}/**/*', recursive=True):

    # It checks if the file is a file.
    if os.path.isfile(file_):

        # It gets the file name of the file.
        file_name = os.path.basename(file_)

        # Checking if the file name contains a period.
        if '.' in file_name:

            # Getting the suffix of the file.
            suffix_name = file_name.split('.')[-1]

        else:

            # Used to classify files that do not have a suffix.
            suffix_name = 'others'

        # It checks if the directory exists. If it does not exist, it creates a new directory in the current working
        # directory.
        if not os.path.exists(f'{target_dir}/{suffix_name}'):

            # It creates a new directory in the current working directory.
            os.mkdir(f'{target_dir}/{suffix_name}')

            # Adding 1 to the variable dir_new_num.
            dir_new_num += 1

        # It copies the file to the target directory.
        shutil.copy(file_, f'{target_dir}/{suffix_name}')

        # Adding 1 to the variable file_move_num.
        file_move_num += 1

注意:为了避免移动文件夹而造成的异常,尤其是系统盘,因此这里用的是复制,也就是shutil.copy函数使用。

最后,将文件分类数量、文件夹新建数量使用print函数进行打印即可。

print(f'整理完成,有{file_move_num}个文件分类到了{dir_new_num}个文件夹中!\n')

input('输入任意键关闭窗口...')

为了避免程序执行完成后直接将命令窗口关闭,上面使用了input函数来保持窗口暂停的效果。

基于Python实现文件分类器的示例代码

基于Python实现文件分类器的示例代码

来源:https://mp.weixin.qq.com/s/9wTbJ2TWJ2owMSxX8I4boQ

0
投稿

猜你喜欢

  • 前言:随着互联网技术的不断发展, MySQL 相关生态也越来越完善,越来越多的工具涌现出来。一些公司或个人纷纷开源出一些不错的工具,本篇文章
  • 使用邻接矩阵实现图及Dijkstra算法# 邻接矩阵实现无向图 Dijkstra算法inf = float("inf")
  • <?php session_start(); $_SESSION['username']="zhuzhao&
  • 使用if…elif…elif…else 实现switch/case可以使用if…elif…elif..else序列来代替switch/cas
  • 拖拽功能主要是用在让用户做一些自定义的动作,比如拖动排序,弹出框拖动移动等等拖拽的流程动作1、鼠标按下 会触发onmousedown事件2、
  • 前言经常看到这种算法可视化的图片,但往往做不到和画图的人心灵相通,所以想自己画一下,本文主要实现归并排序和希尔排序,如果想实现其他算法可参考
  • 前言字符串作为一种重要的Python基本数据类型,在数据处理中发挥着不可或缺的作用,如果对它的方法能够灵活使用,能够达到事半功倍的效果。下面
  • 查看当前数据库支持的引擎show engines+--------------------+---------+--------------
  • 本文详细解说了MySQL Order By Rand()效率优化的方案,并给出了优化的思路过程,是篇不可多得的MySQL Order By
  • 项目功能地图编辑器:可以实现玩家自己定义每一关卡的样式和难易程度运行界面:实现了玩家的移动,跳跃,发射 * ,投掷 * ,以及敌人的AL(移动,
  • 凯撒密码 是密码学中的一种简单的 替换加密 技术。明文中的所有字符都会替换为其按照字母表顺序向左(或向右)偏移一定量后得到的新字母,作为加密
  • 以前没见过这个效果,滚动纵向滚动条看看效果就明白了这样的效果,广告商应该比较喜欢。<!DOCTYPE html PUBLIC &quo
  • 前言mysql中有4类运算符,它们是:算术运算符比较运算符逻辑运算符位操作运算符这个大家应该都比较熟悉,但本文给大家总结介绍的关于MySql
  • 在javascript里怎么样才能把int型转换成string型(1)var  x=100  a  = &nb
  • 在jupyter notebook或者是 Qtconsole下编译运行一个简单的pyqt程序,总是报错:The kernel appears
  • 前言gif图就是动态图,它的原理和视频有点类似,也是通过很多静态图片合成的.本篇文章主要介绍,如何利用Python快速合成gif图,主要利用
  • python 对excel的 读入 与 改写(对比xlwt、openpyxl、xlrd)xlwt不支持写xlsx文件。openpyxl不支持
  • PHP ini_set用来设置php.ini的值,在函数执行的时候生效,脚本结束后,设置失效。无需打开php.ini文件,就能修改配置,对于
  • Python 非常易学,强大的编程语言。Python 包括高效高级的数据结构,提供简单且高效的面向对象编程。Python 的学习过程少不了
  • 首先,我们需要着重介绍一些概念,以给你提供一些使这个“奇迹”得以发生的组成部分。太轻易地泄露伏笔对于讲故事来说不是个好的形式,所以那些不愿意
手机版 网络编程 asp之家 www.aspxhome.com