The os Module
This module provides a portable way of using operating system dependent functionality.
- import os
|Path||A path to a file. The path separator may be determined by |
|Mode||The desired permission, in octal (e.g. |
Change permissions on a file
mode is the desired permission, in octal.
Create a directory
If you need to specify permissions, you can use the optional
Determine the name of the operating system
os module provides an interface to determine what type of operating system the code is currently running on.
This can return one of the following in Python 3:
More detailed information can be retrieved from
Follow a symlink (POSIX)
Sometimes you need to determine the target of a symlink.
os.readlink will do this:
Get current directory
makedirs - recursive directory creation
Given a local directory with the following contents:
We want to create the same subdir1, subdir2 under a new directory dir2, which does not exist yet.
Running this results in
dir2 is only created the first time it is needed, for subdir1's creation.
If we had used os.mkdir instead, we would have had an exception because dir2 would not have existed yet.
os.makedirs won't like it if the target directory exists already. If we re-run it again:
However, this could easily be fixed by catching the exception and checking that the directory has been created.
Remove a directory
Remove the directory at
You should not use
os.remove() to remove a directory. That function is for files and using it on directories will result in an