我有一个名为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
Run Code Online (Sandbox Code Playgroud)
请注意,这仍然是一项正在进行中的工作.它在我眼中非常丑陋......我在这里想要实现的是通过所有文件夹和子文件夹将所有文件名放在名为"list_of_files"的字典中,名称为"key",并且完整路径为"价值".该函数还没有完全正常工作,但是想知道如何使用os.walk函数来做类似的事情?
谢谢
ig0*_*774 55
根据您的简短描述,这样的事情应该有效:
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])
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用生成器,以@ig0774 的代码为基础
import os
def walk_through_files(path, file_extension='.html'):
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
if filename.endswith(file_extension):
yield os.path.join(dirpath, filename)
Run Code Online (Sandbox Code Playgroud)
进而
for fname in walk_through_files():
print(fname)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38959 次 |
| 最近记录: |