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('.'):
    # Here, `the_dir` will always start with a ".".
    print('The dir:  ', the_dir)
    print('Dirs in it: ', dirs)
    print('Files in it:', files)
    print('-' * 10)

Note that while walking the dirs, cwd does not change.

If you want to keep track of how deep you are, you can count slashes:

the_dir.count("/")