• 遍历目录


    转载:https://automatetheboringstuff.com/

    转载:https://automatetheboringstuff.com/2e/chapter10/

    import os
    
    for folderName, subfolders, filenames in os.walk('C:\\delicious'):
        print('The current folder is ' + folderName)
    
        for subfolder in subfolders:
            print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
    
        for filename in filenames:
            print('FILE INSIDE ' + folderName + ': '+ filename)
    
        print('')

    The current folder is C:\delicious                                    第一层
    SUBFOLDER OF C:\delicious: cats
    SUBFOLDER OF C:\delicious: walnut
    FILE INSIDE C:\delicious: spam.txt

    The current folder is C:\delicious\cats                             第二层
    FILE INSIDE C:\delicious\cats: catnames.txt
    FILE INSIDE C:\delicious\cats: zophie.jpg

    The current folder is C:\delicious\walnut                         第二层
    SUBFOLDER OF C:\delicious\walnut: waffles

    The current folder is C:\delicious\walnut\waffles             第三层
    FILE INSIDE C:\delicious\walnut\waffles: butter.txt.

    os.walk()函数传递一个字符串值:一个文件夹的路径。您可以for循环语句中使用os.walk()遍历目录树,就像您可以使用range()函数遍历一系列数字一样。range()不同os.walk()函数在每次循环迭代时将返回三个值:

    • 当前文件夹名称的字符串
    • 当前文件夹中文件夹的字符串列表
    • 当前文件夹中文件的字符串列表

    (在当前文件夹中,我的意思是for循环的当前迭代的文件夹。os.walk()不会更改程序的当前工作目录。)

    就像您可以在代码中为range(10):中的i选择变量名i一样,您也可以为前面列出的三个值选择变量名。我通常使用名称foldername子文件夹文件名

  • 相关阅读:
    Centos7安装配置JDK8
    Jmeter学习笔记
    mysql5.7版本免安装配置教程
    mysql查看线程详解(转载)
    xpath定位方法小结(转载)
    nginx负载均衡的5种策略(转载)
    loadrunner多场景的串行执行以及定时执行
    mysql 远程连接超时解决办法
    JAVA内存构成详解
    jconsole远程连接超时问题解决方法
  • 原文地址:https://www.cnblogs.com/xiaobaibailongma/p/12381104.html
Copyright © 2020-2023  润新知