Python Notes and Examples

Files and Directories

Import io for open.

Import os for chdir, getcwd, listdir, mkdir, remove, rename, walk, etc.

Import os.path for basename, dirname, exists, isdir, getmtime, etc.

Files

import io
# Default mode is 'rt' (read, text).
with io.open('my_file.txt') as f:
    for line in f:
        # get lines one at a time, each still having a newline at the end
    # or
    lines = f.readlines()  # leaves the newlines at the end of each line
    # or
    all_of_it = f.read()
    # do stuff

and the file is automatically closed when we leave the with block.

Directory Walking

import os
for (the_dir, dirs, files) in os.walk('.'):
    print('The dir:  ', the_dir)
    print('Dirs in it: ', dirs)
    print('Files in it:', files)
    print('-' * 10)

Note that while walking the dirs, we do not change our cwd.