Mar. 03, 2013

Having fun with OS.Walk in Python

Overview

OS.walk() generate the file names in a directory tree by walking the tree either
top-down or bottom-up.

For each directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).

Paths
root :  Prints out directories only from what you specified
dirs : Prints out sub-directories from root. 
files:  Prints out all files from root and directories
walkFileSystem.py
Open an text editor , copy & paste the code below.

Save the file as walkFileSystem.py and exit the editor.

Run the script:
$ python walkFileSystem.py
import os

os.system("clear")
print "-" * 80
print "OS Walk Program"
print "-" * 80
print "
"

print "Root prints out directories only from what you specified"
print "-" * 70

print "Dirs prints out sub-directories from root"
print "-" * 70

print "Files prints out all files from root and directories"
print "-" * 70

print "This program will do an os.walk on the folder that you specify"
print "-" * 70

path = raw_input("Specify a folder that you want to perform an 'os.walk' on: >> ")

for root, dirs, files in os.walk(path):

    print root
    print "---------------"

    print dirs
    print "---------------"

    print files
    print "---------------"
More reading can be found here

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.