1.使用os.walk遍历文件目录
import os
sPath = "G:\\test"
# os.walk遍历
s = tuple(os.walk(sPath, True, None, False))
print(s)
2.使用深度遍历方式遍历文件目录
# 深度遍历
def DFS(absPath) :
if (os.path.isabs(absPath)) :
if (os.path.exists(absPath) == False):
print("当前路径不存在")
return
if (os.path.isfile(absPath)) :
return
for v in os.listdir(absPath) :
subPath = os.path.join(absPath, v)
DFS(subPath)
print(subPath)
else :
return
3.删除包含“f”的文件夹
def DelDirByDFS(absPath) :
if (os.path.isfile(absPath)) :
return
if (absPath.find("f") != -1) :
for v in os.listdir(absPath) :
subPath = os.path.join(absPath, v)
if (os.path.isfile(subPath)) :
print("删除文件成功")
os.remove(subPath)
elif (os.path.isdir(subPath)) :
DelDirByDFS(subPath)
print("删除文件夹成功")
os.rmdir(absPath)
return
for v in os.listdir(absPath):
subPath = os.path.join(absPath, v)
if (os.path.isdir(subPath)):
DelDirByDFS(subPath)
4.删除包含“abcd”的文件
def DelFile(absPath) :
if (os.path.isfile(absPath)) :
if (absPath.find("abcd") != -1) :
print("删除文件成功")
os.remove(absPath)
return
for v in os.listdir(absPath):
subPath = os.path.join(absPath, v)
DelFile(subPath)