方法一:使用os.walk()
# -*- coding:utf-8 -*-
import os
def traversalfile(path):
for root,dirs,files in os.walk(path): #root当前根目录;dirs表示当前路径包含文件夹list;files表示当前路径包含文件list
for file in files:
print(file)
if __name__ == '__main__':
filePath = "D:/python"
if os.path.exists(filePath):
traversalfile(filePath)
else:
print(filePath,'not exist!')
exit(0)
方法二:递归
# -*- coding:utf-8 -*-
import os
def getvector(path):
print("getvector ...")
dirLists = os.listdir(path)
print(dirLists)
for dirList in dirLists:
print(dirList)
if os.path.isfile(os.path.join(path,dirList)):
print(os.path.join(path,dirList))
if os.path.isdir(os.path.join(path,dirList)):
print(path)
print(dirList)
getvector(os.path.join(path,dirList))
if __name__ == '__main__':
filePath = "D:/python"
if os.path.exists(filePath):
getvector(filePath)
else:
print(filePath,'not exist!')
exit(0)