The OS Library

Overview

The os library is a useful library that allows you to create python programs that do similar tasks to windows explorer on the windows platform.
Rather than explain this library in detail we are going to cover a few brief examples that allow you to get started and if you want a more advanced feature or something that is not here then this should be covered in the documentation.

Example - Get current directory

Being aware of where a program is running allows you to interact with files that are local to the program.
import os
print (os.getcwd())
This returns:
C:\temp

Example - Change Current Directory

Changing directory example.
import os
print (os.getcwd())
os.chdir(r"C:/temp/python")
print (os.getcwd())
This returns:
C:\temp
C:\temp\python

Example - Return all files in a directory and sub-directories

When a program needs to operate on a bunch of files, you can use the os library to provide a list of files in a directory and all subsequent sub-directories.
This example will search my temp folder and create a list of files that have the .py extension.
filelist = []
fileType = "py"
for root, dirs, files in os.walk(r"C:/temp"):
    for file in files:
        if file.endswith(fileType):
            filelist.append(file)

for f in filelist:
    print (f)     
This returns a list of files.
C:\temp\timer.py
C:\temp\kaggle.py

Example - Get the Username

When creating automated tools for a group of users you may want to automatically input data that is specific to a given user.
print (os.getlogin())
This returns:
Dean



Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.
Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.


Related Pages

Pickle - The pickle library allows a program to save data in a binary file.
Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.
Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter - Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines