【发布时间】:2011-02-24 18:03:21
【问题描述】:
我有一个叫做notes的文件夹,自然会被分类成文件夹,在这些文件夹中也会有子文件夹的子分类。现在我的问题是我有一个遍历 3 级子目录的函数:
def obtainFiles(path):
list_of_files = {}
for element in os.listdir(path):
# if the element is an html file then..
if element[-5:] == ".html":
list_of_files[element] = path + "/" + element
else: # element is a folder therefore a category
category = os.path.join(path, element)
# go through the category dir
for element_2 in os.listdir(category):
dir_level_2 = os.path.join(path,element + "/" + element_2)
if element_2[-5:] == ".html":
print "- found file: " + element_2
# add the file to the list of files
list_of_files[element_2] = dir_level_2
elif os.path.isdir(element_2):
subcategory = dir_level_2
# go through the subcategory dir
for element_3 in os.listdir(subcategory):
subcategory_path = subcategory + "/" + element_3
if subcategory_path[-5:] == ".html":
print "- found file: " + element_3
list_of_files[element_3] = subcategory_path
else:
for element_4 in os.listdir(subcategory_path):
print "- found file:" + element_4
请注意,这仍然是一项正在进行的工作。在我眼里太丑了…… 我在这里想要实现的是遍历所有文件夹和子文件夹,并将所有文件名放在一个名为“list_of_files”的字典中,名称为“key”,完整路径为“value”。该函数目前还不能很好地工作,但想知道如何使用 os.walk 函数来做类似的事情?
谢谢
【问题讨论】:
-
要回答这个问题,首先要了解递归。另见:*.com/questions/2922783/…
标签: python