Python’s lightweight dynamic interface is proven excellent for networking, data scraping and gui generating tasks. Python’s powerful and possibly overlooked os module enables you to take a dynamic approach to operating system programming. With python you can read or write to and from files across different areas on your hard drive and interface with the cmd line simply utilizing a few lines of code. This becomes useful in managing dependencies and project states.
First import sys and os
# lister.py import sys, os
Then we will create a new method lets call it lister which will take an argument root to create our directory tree. The for loop will iterate through each directory containing files and os.walk() will generate a list of directories either top-down or bottom-up. This will print each directory to the command line console encapsulated by braces.
def lister(root): ....for (thisdir, subshere, fileshere) in os.walk(root): ........print('[' + thisdir + ']')
Each directory at its root yields a tuple containing three variables: dirpath, dirnames, filenames. These variables make up a tree-like data structure (where * represents many).
The nested for loop iterates through all the files contained by the directory.
........for fname in fileshere: ............path = os.path.join(thisdir, fname) ............print(path)
The path is collected and concatenated with the filename and then printed to the console.
if __name__ == '__main__': ....lister(sys.argv)
When lister.py is run the root directory must be called with the root directory to pass as an argument so sys knows where to begin the os walk.
The resulting output might be similar to the stream below.
If you like these blog posts or want to comment and or share something do so below and follow py-guy!