遍历目录
作者:互联网
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\b 27 # print(name) # name 为 目录下的文件或目录名称(相对路径,路径不全) 28 # 拼接绝对路径 29 tempPath = os.path.join(path, name) # ...\a\a1.txt # ...\a\b 30 # print(tempPath) 31 # 判断新的路径是否为文件 32 if os.path.isfile(tempPath): 33 print("文件为:", name) 34 # print("文件为:", tempPath) 35 elif os.path.isdir(tempPath): # ...\a\b\c 36 print("目录为:", name) 37 # print("目录为:", tempPath) 38 getFilesAndDirectories(tempPath) # .....a\b\c 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] --
标签:遍历,name,tempPath,print,path,txt,os,目录 来源: https://www.cnblogs.com/BKY88888888/p/11272289.html