Browse files and subfolders in Python
You can use os.walk()
to recursively iterate through a directory and all its subdirectories:
for root, dirs, files in os.walk(path): for name in files: if name.endswith((".html", ".htm")): # whatever
To build a list of these names, you can use a list comprehension:
htmlfiles = [os.path.join(root, name) for root, dirs, files in os.walk(path) for name in files if name.endswith((".html", ".htm"))]
I had a similar thing to work on, and this is how I did it.
import osrootdir = os.getcwd()for subdir, dirs, files in os.walk(rootdir): for file in files: #print os.path.join(subdir, file) filepath = subdir + os.sep + file if filepath.endswith(".html"): print (filepath)
Hope this helps.
In python 3 you can use os.scandir():
for i in os.scandir(path): if i.is_file(): print('File: ' + i.path) elif i.is_dir(): print('Folder: ' + i.path)