Python OS module

Operating system interface.

Module #

import os

For a listing of all the methods (there’s a bunch, so this set of notes won’t be anywhere near complete):

print(dir(os))

Current directory #

Get current working directory.

print(os.getcwd())

Change directory #

os.chdir('<path specification>')

List files and directories #

print(os.listdir())

Optionally, specificy a path.

Create directory #

os.mkdir('<directory path and name>')

This allows for the creation of nested directory structures:

os.mkdirs('<directory path and name>')

Delete directories #

Does not remove intermediate directories:

os.rmdir('<directory specification>')

Removes intermediate directories (dangerous!):

os.removedirs('<directory specification>')

Rename #

os.rename('<original name>', '<new name>')

Details about files and directories #

print(os.stat('<path specification>'))

There are a lot of details. Specific details can be pulled with dot notation. For instance, to get size:

print(os.stat('<path specification>').st_size)

Or modification time:

mod_time = os.stat('<path specification>').st_mtime

# to convert datetime to human-readable format
from datetime import datetime

print(datetime.fromtimestamp(mod_time))

Traverse directory tree #

Kind of like tree.

Generator that creates tuple of three values – directory path, directories in that path, files.

os.walk()

Break out each element:

for dirpath, dirnames, filenames in os.walk('<path specification>'):
    print(dirpath)
    print(dirnames)
    print(filenames)

Access environment variables #

Also see notes specifically on environment variables.

Get home directory:

os.environ.get('HOME')

Handling paths #

Create a complete path, handles slashes properly:

os.path.join('<directory specification>', '<file specification>')

Extract part of a path #

Sometimes, there’s a need to extract just a part of a path.

path = "$HOME/a/b/c/file

os.sep
# '/' 

path_parts = path.split(os.sep)

path_parts[<index>]