Python Cheat Sheets

Page Contents

Date/Time

# Date/time as a string using time module
import time
time.strftime('%Y%m%d%H%M%S')

# Date/time as a string using datetime module
import datetime
datetime.datetime.today().strftime('%Y%m%d%H%M%S')

Files/Directories

# Find all .txt files under /some/dir
for rootDir, subDirs, files in os.walk(dirToScan):
   for fname in files:
      if fnmatch.fnmatch(fname, mask):
         yield (rootDir, fname)
for dir, file in YieldFiles("/some/dir", "*.txt")
   print file

Signals

import signal

# Somewhere in your initialisation
signal.signal(signal.SIGINT, signal_handler)

def signal_handler(signal, frame):
   # Clean up etc
   sys.exit(1)