• 技术文章 >Python技术 >Python基础教程

    Python中如何编写辅助模块module?

    小妮浅浅小妮浅浅2021-02-21 16:40:18原创2322

    必须编写一个辅助整理模块,打开名为module.py的Python文件。

    1、Directory类

    在module.py中打开,输入:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    # 导入所需的模块

    import os

    import shutil

      

    # 先把路径设置为你需要整理的文件夹的路径

    path = r"C:\Python\Python整理文件\我的文件夹"

      

    # 定义Directory类

    class Directory():

        def __init__(self, directory_name, file_suffix):

         # 参数:文件夹名 文件后缀名

            self.file_suffix = file_suffix

            self.directory_name = directory_name

            # 要保存的文件

            self.file_list = []

      

        def add_file(self, file_name):

         # 获取文件后缀名 并判断是否在file_suffix列表中

            if file_name.split('.')[-1] in self.file_suffix:

             # 如果有 则添加到file_list

                self.file_list.append(file_name)

                return True

            else:

                return False

                 

    def save_files(self):

    # 这个方法用于保存已经添加的文件

    # 首先使用mkdir函数创建文件夹

            os.mkdir(path + "\\" + self.directory_name)

            for file in self.file_list:

             # 再使用move函数一个一个移动文件

                shutil.move(path + "\\" + file, path + "\\" + self.directory_name)

    定义Directory类是为了便于统一管理文件。第一个,获取参数:要保存的文件夹的名称,文件后缀名称(列表)。文件后缀名这个参数是为了判断保存哪些后缀名符合要求的文件。

    在add_file(fille_name)中传入一个文件名,该文件的后缀名决定是否进行存储,如果合格,则加入存储列表,返回True,否则返回False。

    save_files()用来保存添加到file_list中的文件,首先自动创建一个名为directory_name的属性的文件夹,然后使用shutil.move函数将文件移动到已创建的文件夹中。

    2、Directories类

    为了使管理更加方便,在module.py中添加了Directories类,使Directory类的管理更加方便。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    class Directories():

        def __init__(self, *directories):

         # 传入需要管理的Directory类 参数数量制

            self.directories = directories

      

    # 传入文件名

        def add_file(self, file_name):

            for directory in self.directories:

             # 挨个执行Directory类中的add_file函数

             # 直至符合存储条件

                if directory.add_file(file_name):

                    break

    # 遍历每个Directory类

    # 并且执行Directory类的save_files函数保存

        def save_files(self):

            for directory in self.directories:

                directory.save_files()

    以上就是Python中编写辅助模块module的方法,希望能对大家有所帮助!

    专题推荐:python module
    上一篇:python中exec()函数如何执行表达式? 下一篇:python的递归函数如何理解?

    相关文章推荐

    • Python中使用K-means算法• python入门:方差和标准差的区别• python如何实现均方误差和均方根误差?• Python字典遍历的三种情况• python变量作用域是什么?• Python中if嵌套是什么?• python中exec()函数如何执行表达式?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网