如何使用python遍历目录?

2024-06-24 13:07:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为notes的文件夹,它们自然会被分类到文件夹中,在这些文件夹中,也会有子文件夹用于子类别。现在我的问题是我有一个函数,它可以遍历三个级别的子目录:

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函数来做类似的事情?

谢谢


Tags: ofthepathin文件夹forifos
3条回答

根据你的简短描述,这样的方法应该有效:

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])

你可以这样做:

list_of_files = dict([ (file, os.sep.join((dir, file)))
                       for (dir,dirs,files) in os.walk(path)
                       for file in files
                       if file[-5:] == '.html' ])

另一种选择是使用发电机,以@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)

然后

for fname in walk_through_files():
    print(fname)

相关问题 更多 >