作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我有一个叫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 函数来做类似的事情?
谢谢
最佳答案
根据您的简短描述,这样的事情应该可以工作:
list_of_files = {}
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
if filename.endswith('.html'):
list_of_files[filename] = os.sep.join([dirpath, filename])
关于python - 你如何使用 python 遍历目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2922783/
我是一名优秀的程序员,十分优秀!