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
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())
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 @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)
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' ])