#
#使用递归来漫游文件目录
import os
def list_walk(root_dir):
# 返回root_dir目录下的所有文件和子目录,并遍历
for item in os.listdir(root_dir):
item_path = os.path.join(root_dir, item)
if os.path.isdir(item_path):
print("子目录", item_path)
list_walk(item_path)
else:
print("文件", item_path)
root_directory = 'D:/python爬虫/爬虫作业'
list_walk(root_directory)
# 使用os.walk漫游文件目录
import os
def list_path(root):
# 生成器,生成一个三元组, 遍历到的目录路径,"dirpath 是当前遍历到的目录的路径。dirnames
# 是一个列表,包含当前目录下的所有子目录名。filenames 是一个列表,包含当前目录下的所有文件名。"
# 从下到上遍历
# for dirpath, dirnames, filenames in os.walk(root, topdown=False):
for dirpath, dirnames, filenames in os.walk(root):
print(f"当前目录:{dirpath}")
print("子目录")
for dirname in dirnames:
print(f"-----{dirname}")
print("文件")
for filename in filenames:
print(f"------{filename}")
print('-'*35)
list_path('D:/python爬虫/爬虫作业')
漫游文件目录的两种方法
最新推荐文章于 2024-10-18 22:48:33 发布