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

    python如何遍历文件夹

    小妮浅浅小妮浅浅2021-04-22 09:49:45原创9352

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    1、使用 os.walk(folder) 函数,folder就是想要搜索的文件夹的最顶层。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    base/

    ├── fileA.txt

    ├── fileA2.xls

    ├── fileA3.xls

    ├── fileA4.pdf

    ├── sub1

    │   ├── fileB.txt

    │   ├── fileB2.xls

    │   └── fileB3.pdf

    └── sub2

        ├── fileB.txt

        ├── fileC2.xls

        └── fileC3.pdf

    2、使用递归的方法

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    import os

    files = list()

    def dirAll(pathname):

        if os.path.exists(pathname):

            filelist = os.listdir(pathname)

            for f in filelist:

                f = os.path.join(pathname, f)

                if os.path.isdir(f):

                    dirAll(f)

                else:

                    dirname = os.path.dirname(f)

                    baseName = os.path.basename(f)

                    if dirname.endswith(os.sep):

                        files.append(dirname+baseName)

                    else:

                        files.append(dirname+os.sep+baseName)

      

      

    dirAll("/Users/cxhuan/Downloads/globtest/hello")

    for f in files:

        print(f)

    3、glob是python附带的操作文件模块,以简洁实用而闻名。该模块的功能比较简单,使用方便。主要用于寻找符合特定规则的文件路径。

    1

    2

    3

    * : 匹配0个或多个字符;

    ? : 匹配单个字符;

    [] :匹配指定范围内的字符,如:[0-9]匹配数字。

    以上就是python遍历文件夹的方法,本篇一共总结了三种遍历的操作,分别是os.walk函数、递归和glob操作文件模块,大家对它们的基本用法进行理解后,可以运行上面的代码部分。更多Python学习指路:python基础教程

    专题推荐:python遍历
    上一篇:python如何读取文件名 下一篇:python如何处理文件

    相关文章推荐

    • 如何用Python遍历ini文件?• python有几种循环遍历的方法?• python使用items()遍历键值对• php遍历文件夹• php递归遍历文件夹• java数组如何遍历全部的元素• python遍历查看csv文件• python如何用循环遍历分离数据

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网