How do you walk through the directories using python?

前端 未结 4 1495
长情又很酷
长情又很酷 2020-12-15 17:23

I have a folder called notes, naturally they will be categorized into folders, and within those folders there will also be sub-folders for sub categories. Now my problem is

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 17:57

    an alternative is to use generator, building on @ig0774's code

    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)
    

    and then

    for fname in walk_through_files():
        print(fname)
    

提交回复
热议问题