How do you walk through the directories using python?

How do you walk through the directories using python?

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

an alternative is to use generator, building on @ig0774s 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)

How do you walk through the directories using python?

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

Heres 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())
                
            

Leave a Reply

Your email address will not be published. Required fields are marked *