Python Operating System Calls

12/13/2017

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

                                                        Screen Shot 2017-12-13 at 2.06.33 PM.png

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

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.

Screen Shot 2017-12-13 at 2.13.26 PM

The resulting output might be similar to the stream below.

Screen Shot 2017-12-13 at 2.12.33 PM.png

If you like these blog posts or want to comment and or share something do so below and follow py-guy!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s