目录遍历
import os
def fun1(path1):
stack = [] #设定一个列表
stack.append(path1)
# print(stack)
while len(stack) != 0 :
path1 = stack.pop() #列表后进先出
dir_path = os.listdir(path1)
for i in dir_path:
if os.path.isdir(os.path.join(path1,i)): #判断绝对路径下文件是普通文件还是目录
print("是目录:",i)
stack.append(os.path.join(path1,i)) #普通文件压栈
else:
print("不是目录:",i)
fun1(r'D:\python_code')
——————————————————————————————————————————————————————————————————————————————
import os
def fun1(path1,sp):
sp += ' '
for i in os.listdir(path1):
if os.path.isdir(os.path.join(path1,i)):
print(sp,"是目录:",i)
fun1(os.path.join(path1,i),sp)
else:
print(sp,"是普通文件:",i)
fun1(r'D:\python_code','')
——————————————————————————————————————————————————————
import os
import collections
def fun1(path1):
queue = collections.deque()
queue.append(path1)
# print(queue)
while len(queue) != 0 :
path1 = queue.popleft()
dir_path = os.listdir(path1)
for i in dir_path:
if os.path.isdir(os.path.join(path1,i)):
print("是目录:",i)
queue.append(os.path.join(path1,i))
else:
print("不是目录:",i)
fun1(r'D:\python_code\test1')
我们之间的距离很近,但又很遥远