Python Notes and Examples
← prev | next →     Top-level ToC     /files-and-dirs.html     (printable version)

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

1 Files

# Default mode is 'rt' (read, text).
with 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 =
    # do stuff

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

2 Directory Walking

import os
for (this_dir, dirs_here, files_here) in os.walk('.'):
    print('This dir:  ', this_dir)
    print('Files here:', files_here)
    print('-' * 10)