The os Module


A Byte of Python 

Go to the Table of Contents. Visit the Gifcom web site.

This module represents generic operating system functionality. This module is especially important if you want to make your programs platform-independent i.e. it allows the program to be written such that it will run on Linux as well as Windows without any problems and without requiring changes. An example of this is using the os.sep variable instead of the operation system-specific path separator.

Some of the more useful parts of the os module are listed below Most of them are self-explanatory.

  • The os.name string specifies which platform you are using, such as 'nt' for Windows and 'posix' for Linux/Unix users.

  • The os.getcwd() function gets the current working directory i.e. the path of the directory from which the curent Python script is working.

  • The os.getenv() and os.putenv() functions are used to get and set environment variables respectively.

  • The os.listdir() function returns the name of all files and directories in the specified directory.

  • The os.remove() function is used to delete a file.

  • The os.system() function is used to run a shell command.

  • The os.linesep string gives the line terminator used in the current platform. For example, Windows uses '\r\n', Linux uses '\n' and Mac uses '\r'.

  • The os.path.split() function returns the directory name and file name of the path.

    				
    >>> os.path.split('/home/swaroop/byte/code/poem.txt')
    ('/home/swaroop/byte/code', 'poem.txt')
    				
    				
  • The os.path.isfile() and the os.path.isdir() functions check if the given path refers to a file or directory respectively. Similarly, the os.path.exists() function is used to check if a given path actually exists.

You can explore the Python Standard Documentation for more details on these functions and variables. You can use help(sys), etc. as well.

Summary

We have seen some of the functionality of the sys module and sys modules in the Python Standard Library. You should explore the Python Standard Documentation to find out more about these and other modules as well.

Next, we will cover various aspects of Python that will make our tour of Python more complete.