stack
栈就是先进后出
mystack=[] #列表
mystack.append(1)
mystack.append(2)
mystack.append(3)
while len(mystack)!=0: #胃不空,继续吐
value=mystack.pop() #获取吐出的值
print(value)
queue
队列先进先出
#print("queue")
import collections
myqueue=collections.deque([])#空队列
myqueue.append(1)
myqueue.append(11)
myqueue.append(123)
#print(myqueue.popleft())
#print(myqueue.popleft())
print(myqueue.popleft())
文件列表
调用os,有两个判断的函数:listdir与isdir,前者输出文件名字,后者判断是不是文件夹。我们先选择一个文件夹,利用os打印文件名,再在文件中挨个打印出绝对路径
import os
dirpath=r"C:\Users\Tsinghua-yincheng\Desktop\YinchengDay6Down"
filelist=os.listdir(dirpath) #列举列表,文件名
print(filelist)
for filename in filelist:
filepath=dirpath+"\\"+filename #拼接绝对路径
print(filepath,os.path.isdir(filepath))
如何深度遍历文件夹里每一个文件
先指定文件路径,创建一个空的栈,将路径压入栈中,循环判断只要栈不为空,就pop出一个路径,判断是否有文件夹,有的话打印出来,并且列举出文件夹下所有文件名,遍历所有的文件名,使得每个文件前面加上path变成绝对路径,在判断一下如果有文件夹则将其压入栈,否则打印文件路径,退出循环后,再次打印文件path。
简而言之,先将文件夹名压入栈再一个个看文件名。
import os
rootpath=r"C:\Users\Tsinghua-yincheng\Desktop\tools\MemSearch"
mystack=[]
mystack.append(rootpath)
while len(mystack)!=0:
path=mystack.pop()#弹出的路径
if os.path.isdir(path):
print("文件夹 ",path)
filenamelist=os.listdir(path) #列举文件夹下所有文件名
for filename in filenamelist:#遍历所有文件名
filepath=os.path.join(path,filename)#取得绝对路径
if os.path.isdir(filepath):
mystack.append(filepath) #文件夹,压入栈
else:
print("文件 ",filepath)
else:
print("文件 ",path)
'''
1
--2
----3
'''
深度遍历层次感
打印出来会发现有“----”来使得每一个文件夹里的文件呈现阶梯状的层次感
import os
rootpath=r"C:\Users\Tsinghua-yincheng\Desktop\YinchengDay6Down"
mystack=[]
mystack.append([rootpath,0])#rootpath,路径
while len(mystack)!=0:
pathlist=mystack.pop()#弹出的路径
num=pathlist[1] #取出层次
headstr=""
for i in range(num):
headstr+="----"
#每一层的前缀,显示一层
if os.path.isdir(pathlist[0]):
print(headstr,"文件夹 ",pathlist[0])
num+=1
headstr+="----" #层次 +1,
filenamelist=os.listdir(pathlist[0]) #列举文件夹下所有文件名
for filename in filenamelist:#遍历所有文件名
filepath=os.path.join(pathlist[0],filename)#取得绝对路径
if os.path.isdir(filepath):
mystack.append([filepath,num]) #文件夹,压入栈
else:
print(headstr,"文件 ",filepath)
else:
print(headstr,"文件 ",pathlist[0])
'''
1
--2
----3
'''
文件夹广度遍历
广度遍历利用collections创建一个空的队列,将路径压入队列,若队列不为空,那么取出队列,遍历文件夹,如果只有文件就是空集合,然后遍历文件夹里的每一个文件夹,压入队列,如果有文件就打印出来。
简而言之,先打印文件夹里的文件再深入文件夹。
import os
import collections
path=r"C:\Users\Tsinghua-yincheng\Desktop\YinchengDay6Down"
myqueue=collections.deque([])#空队列
myqueue.append(path)
while len(myqueue)!=0:
path=myqueue.popleft()#取出路径
filelist=os.listdir(path)#遍历文件夹,如果是文件就是空集合
for filename in filelist:
filepath=os.path.join(path,filename)#绝对路径
if os.path.isdir(filepath):
print("文件夹",filepath)
myqueue.append(filepath)
else:
print("文件",filepath)