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

     1 # 栈   队列   递归
     2 
     3 # 使用递归遍历目录
     4 import os
     5 # "C:\Users\xlg\Desktop\a"
     6 # os.listdir("")
     7 # os.path.isdir()
     8 # os.path.isfile()
     9 # os.path.join()
    10 '''
    11 path = "C:\Users\xlg\Desktop\a"
    12 for dirandfile in os.listdir(path):
    13     # print(dirandfile)
    14     newPath = os.path.join(path, dirandfile)
    15     if os.path.isfile(newPath):
    16         print("file:",newPath)
    17     elif os.path.isdir(newPath):
    18         for i in os.listdir(newPath):
    19             print(i)
    20 '''
    21 path = "C:\Users\xlg\Desktop\a"
    22 
    23 # 遍历目录的方法
    24 def getFilesAndDirectories(path):  # .....a
    25     # 遍历目录下的文件及目录
    26     for name in os.listdir(path):  #  ....a
    27         # print(name)  # name 为 目录下的文件或目录名称(相对路径,路径不全)
    28         # 拼接绝对路径
    29         tempPath = os.path.join(path, name)  # ...aa1.txt  # ...a
    30         # print(tempPath)
    31         # 判断新的路径是否为文件
    32         if os.path.isfile(tempPath):
    33             print("文件为:", name)
    34             # print("文件为:", tempPath)
    35         elif os.path.isdir(tempPath):   # ...ac
    36             print("目录为:", name)
    37             # print("目录为:", tempPath)
    38             getFilesAndDirectories(tempPath)  # .....ac
    39 
    40 getFilesAndDirectories(path)
    41 
    42 # a -- b c   a1.txt
    43 # b --- d b1.txt
    44 # c -- c1.txt  c2.txt
    45 #
    46 # d --- d1.txt  d2.txt
    47 
    48 # [a]
    49 # [c, b]   -- [c, d]   -- [c]  --
  • 相关阅读:
    GCD与LCM
    命名空间的使用
    [模板][持续更新]欧拉回路与欧拉路径浅析
    二进制GCD算法解析
    [模板]LCA的倍增求法解析
    [模板]字符串哈希的简易做法
    11、Android--屏幕适配
    10、Android--Shape
    09、Android--Fragment
    08、Android--BroadcastReceiver
  • 原文地址:https://www.cnblogs.com/BKY88888888/p/11272289.html
Copyright © 2011-2022 走看看