zoukankan      html  css  js  c++  java
  • 遍历目录

    转载: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子文件夹文件名

  • 相关阅读:
    yii2美化url
    Android 百度地图API 定位 导航
    辛星浅谈PHP的混乱的编码风格
    html5非常火,他究竟与html4有何差别?
    Cocos2d-x 3.0心得(01)-图片载入与混合模式
    解读BOM与COM
    HDU 1718 Rank counting sort解法
    汉语转拼音pinyin4j
    UVALive-6656-Watching the Kangaroo(二分)
    thinPHP中多维数组的遍历
  • 原文地址:https://www.cnblogs.com/xiaobaibailongma/p/12381104.html
Copyright © 2011-2022 走看看