How do you walk through the directories using python?

前端 未结 4 1485
长情又很酷
长情又很酷 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:43

    I've come across this question multiple times, and none of the answers satisfy me - so created a script for that. Pytohn is very cumbersome to use when it comes to walking through directories.

    Here's how it can be used:

    import file_walker
    
    
    for f in file_walker.walk("/a/path"):
         print(f.name, f.full_path) # Name is without extension
         if f.isDirectory: # Check if object is directory
             for sub_f in f.walk(): # Easily walk on new levels
                 if sub_f.isFile: # Check if object is file (= !isDirectory)
                     print(sub_f.extension) # Print file extension
                     with sub_f.open("r") as open_f: # Easily open file
                         print(open_f.read())
    
    0 讨论(0)
  • 2020-12-15 17:44

    Based on your short descriptions, something like this should work:

    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])
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-15 18:02

    You could do this:

    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' ])
    
    0 讨论(0)
提交回复
热议问题