2. os module

Python os module can be used to perform tasks such as finding the name of present working directory, changing current working directory, checking if certain files or directories exist at a location, creating new directories, deleting existing files or directories, walking through a directory and performing operations on every file in the directory that satisfies some user-defined criteria, and a lot more. The following notes show how to do some of these things with the os module. If you don’t find what you are looking for below, you can try http://docs.python.org/library/os.html

For the examples below suppose we are in a directory try_python_os whose full path is /Users/coolpython/try_python_os and it has the following structure:

dir1
    way_in.py
apple.py
try_os.py

That is, try_python_os contains one directory dir1 (which contains a file way_in.py) and two files: apple.py and try_os.py.

2.1. Finding Information about the current working directory

To get the complete path of the current working directory enter:

import os
os.getcwd()

Note that if you have already imported the os module, you do not need the line import os.

An alternative way of doing this is:

import os
os.path.abspath('.')

If you want a list of all files and directories in the current directory:

import os
os.listdir('.')

This will return:

['apple.py', 'dir1', 'try_os.py']

2.2. Change to another directory

This can be done by using os.chdir(path_to_new_directory) command. For example, suppose

os.getcwd()

returns (assuming that you have already imported the os module)

'/Users/coolpython/try_python_os'

That is, we are in directory try_python_os and we want to make dir1 inside try_python_os as our current working directory. We can do this using the command:

os.chdir('./dir1')

We can go back to the parent directory of dir using:

os.chdir('../')

The above two examples use relative paths to change directories. You can also enter the absolute path to do so.

2.3. Creating Directories

Suppose you want to make another directory named dir2 within try_python_os. You can do so using:

import os
os.mkdir('Users/coolpython/try_python_os/dir2')

This will work regardless of your location because you are using the absolute path name. If current working directory is Users/coolpython/try_python_os you can also make a new directory within try_python_os using relative path name, as in this example:

import os
os.mkdir('./dir2')

Note that if a directory already exists when you try to create it, you will get an OSError. One possible work around is to test whether the directory exists and then use the mkdir command only if the directory does not exist. This can be done using os.path.exists method:

import os
if os.path.exists('./dir2'):
    pass
else:
    os.mkdir('./dir2')

One problem using this method is that if there exists a file named dir2 in try_python_os then the above code snippet will not create a directory dir2 (because os.path.exists('./dir2') will return True). To prevent this from happening you can instead use os.path.isdir() to check the existence of a directory. For example, instead of the above code-snippet you can do the following:

import os
if os.path.isdir('./dir2'):
    pass
else:
    os.mkdir('./dir2')

2.4. Extracting filename from a given path

Suppose you have a path to a file (either absolute or relative) and you want to extract the filename from this path. You can do this using os.path.basename. For example:

import os
os.path.basename('/Users/somename/somedirectory/pythoniscool.txt')

will return pythoniscool.txt.

Another way to do this is to use os.path.split, which returns a tuple of two elements: first is the head of the path containing everything before the last ‘/’ and the second element is the tail containing everything after the last ‘/’.

For example:

import os
os.path.split('/Users/somename/somedirectory/pythoniscool.txt')

returns

('/Users/somename/somedirectory', 'pythoniscool.txt')

Hence, you can use os.path.split('/Users/somename/somedirectory/pythoniscool.txt')[1] to extract the filename from the path.