Python Cheat Sheet

Contents:
IO   Data Structures  Strings  Admin, os, sys  Control Flow  Big Templates


IO Back to Contents

readFile2String 1 liner

f = open('c:/test.txt', 'r'); s = f.read(); f.close()

readFile2String

f = open('c:/', 'r') #on windows add 'b'==binary
s = f.read()
f.close()

readLines 1 liner

for line in file('fileName.txt').readlines()

readLines

f = open('c:/', 'r') #on windows add 'b'==binary
for line in f:
    # process(line)
f.close()

writeString 1 liner

f = open('c:/', 'w'); f.write('This is a test\n'); f.close()

writeString

f = open('c:/', 'w') #on windows add 'b'==binary
f.write('This is a test\n')  # newline is NOT automatically added!
f.close()

Data Structures Back to Contents

looping dicts

for k, v in knights.iteritems():
    print k, v

looping enumerate sequences

for i, v in enumerate(Seq):
    print i, v

dict from k v lists

dict(zip(keyList, valList))

dict from k v strings

dict(zip(keyStr.split(' '), valString.split(' ')))

dict from obj attribs

dict((name, getattr(ob, name)) for name in dir(ob) if not name.startswith('__'))

map cube(x)

seq = range(10)
def cube(x): return x*x*x
map(cube, seq)

map add(x,y)

seq = range(10)
def add(x, y): return x+y
map(add, seq, seq)

reduce

seq = range(10)
def add(x, y): return x+y
reduce(add, seq)

list2string

s = ''.join(L)

list creations

L = s.split('#')
iota=range(5)
zeros=[0]*5
foos=['foo']*8
L=[0,1,2] + [3,4]
four=L[-1]
three=L[-2]
zero_1=L[:2]
two_3_4=L[2:]
one_2_3=L[1:4]
del(L[1])
listoflists=[ [0]*4 ] *5
listoflists=[[0]*4 for i in range(5)]

list comprehension [simple]

vec = [2, 4, 6]
[3*x for x in vec]

list comprehension [if]

vec = [2, 4, 6]
[3*x for x in vec if x > 3]

list comprehension [->list]

vec = [2, 4, 6]
[[x,x**2] for x in vec]

list comprehension [->dict]

l1=1,2,3,4,5; l2=6,7,8,9,0
dict([(k, v) for k,v in zip(l1,l2)])
# {1: 6, 2: 7, 3: 8, 4: 9, 5: 0}

list comprehension [v1, v2]

vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
[x*y for x in vec1 for y in vec2]
# rightmost for varies first
# [8, 6, -18, 16, 12, -36, 24, 18, -54]

list comprehension [->tuples l1, l2]

l1=1,2,3; l2=6,7,8
[{x:y} for x in l1 for y in l2]
# rightmost for varies first
# [{1: 6}, {1: 7}, {1: 8}, {2: 6}, {2: 7}, {2: 8}, {3: 6}, {3: 7}, {3: 8}]

list comprehension [nested]

mat = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
      ]
[[row[i] for row in mat] for i in range(len(mat[0]))]
# Above list comprehension inverts the matrix
# :)To avoid apprehension when nesting list comprehensions,
#    read them from right to left. :)

zip

x = ['1', '2', '3']
y = ('4', '5', '6')
z = "789"
zip(x, y, z)
# [('1', '4', '7'), ('2', '5', '8'), ('3', '6', '9')]
# returns a list of tuples, where the i-th tuple contains the i-th
#   element from each of the argument sequences or iterables.

sorted dict print formatted

cnid = chordNameIntervalDict= {
    'maj':    (0,  4,  7),
    'min':    (0,  3,  7),
    'aug':    (0,  4,  8),
    'dim':    (0,  3,  6),
    'sus2':   (0,  2,  7),
    'sus4':   (0,  5,  7),
    '6':      (0,  4,  7,  9),
    'm6':     (0,  3,  7,  9),
    '7':      (0,  4,  7, 10),
    'maj7':   (0,  4,  7, 11),
    'm7':     (0,  3,  7, 10),
    'dim7':   (0,  3,  6, 10),
    }

#make the keys be the vals and the vals the keys
icnd = intervalChordNameDict = dict([(cnid[k],k) for k in cnid.keys()])

chordNameL = 'maj,min,aug,dim,sus2,sus4,6,m6,7,maj7,m7,dim7'.split(',')

print 'cnid'
for k in chordNameL:
    print ('%7s %s')%(str(k),str(cnid[k]))

print 'icnd'
for k in sorted(icnd):
    print ('%-16s %s ')%(k, icnd[k])

Strings Back to Contents

concat strings

''.join([xStr, yStr])

concat strings [s = concat(s,x)]

xStr = ''.join([xStr, yStr])

string.replace

s = 'spam bacon ham spam ham bacon spam'
s.replace('spam', 'eggs',1) #one
s.replace('spam', 'eggs')   #all

string2list

L = list(s)

string2list [split]

L = s.split('#')

list2string

s = ''.join(L)

enum_string 2 dict

enum_string = es = "state, county, city_state, city_name, city_url"
ed = dict(zip(es.split(", "), range(len(es))))
print ed
{'county': 1, 'city_name': 3, 'state': 0, 'city_url': 4, 'city_state': 2}

Admin, os, sys Back to Contents

cd

import os
os.chdir(r"F:\1d\GoogleDev\AppEnginePjs")

pwd

import os
os.path.abspath(os.curdir)

sys.path.append

import sys
if not('.' in sys.path): sys.path.append('.')

Timestamp

import datetime
str(datetime.datetime.now()).replace(':', '.')
#out: 2011-05-30 11.32.56.375000   [no colons -> good 4 file names

Control Flow Back to Contents

Conditional Expressions

x = true_value if condition else false_value

try except

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

yield

def genBarItems(self):
    rval = ()
    for staffIx, staff in enumerate(self.staves):
        BARS = 1
        for barIx, bar in enumerate(staff[BARS]):
            for itIx, it in enumerate(bar):
                rval = (staffIx, barIx, itIx, it)
                yield rval

Big Templates Back to Contents

class

class BankAccount(object):
    def __init__(self, initial_balance=0):
        self.balance = initial_balance
    def deposit(self, amount):
        self.balance += amount
    def withdraw(self, amount):
        self.balance -= amount
    def overdrawn(self):
        return self.balance < 0
my_account = BankAccount(15)
my_account.withdraw(5)
print my_account.balance

Main

"""example.py DoesSomething to infilename Producing outfilename
Usage:   example.py infileName outfileName
Example: example.py myInFile   myOutfile
"""
import sys

def myFunc(myArg1, myArg2):
    s = raw_input('input a string')
    print s

NUM_ARGS = 2
def main():
    args = sys.argv[1:]
    if len(args) != NUM_ARGS or "-h" in args or "--help" in args:
        print __doc__
        sys.exit(2)
    myFunc(args[0], args[1])

if __name__ == '__main__':
    main()

GUI

# -*- coding: ISO-8859-1 -*-
import sys, time

if not('.' in sys.path): sys.path.append('.')
import midi24txt 

from Tkinter import *
from tkFileDialog import *

# thinking in tkinter http://www.ferg.org/thinking_in_tkinter/all_programs.html

class TheGui:
    def __init__(self, parent):
        #------- frmSetup ----------#
        self.frmSetup = Frame(parent, bd=5)
        self.frmSetup.pack()

        self.inChoices = ('Text', 'Midi')
        self.varRadio = IntVar()

        self.r1 = Radiobutton(self.frmSetup, text="Convert Text INPUT into Midi OUTPUT",
            variable=self.varRadio, value=0, command=self.selRadio)
        self.r1.pack(anchor=W)

        self.r2 = Radiobutton(self.frmSetup, text="Convert Midi INPUT into Text OUTPUT",
            variable=self.varRadio, value=1, command=self.selRadio)
        self.r2.pack(anchor=W)
        #------- frmSetup ----------#

        sep = Frame(parent, width=1, bd=5, bg='black')
        sep.pack(fill=X, expand=1)

        #------- frmIn ----------#
        # http://effbot.org/tkinterbook/tkinter-widget-styling.htm
        self.frmIn = Frame(parent, bd=5)
        self.frmIn.pack()

        self.lblIn = Label(self.frmIn, text='Text Input File Path', width=20)
        self.lblIn.pack(side=LEFT)	

        self.inFilePath = StringVar() # http://effbot.org/tkinterbook/entry.htm
        self.entIn = Entry(self.frmIn, width=20, textvariable=self.inFilePath)
        self.entIn.pack(side=LEFT)

        self.btnIn = Button(self.frmIn, text='Browse', command=self.btnInBrowseClick)
        self.btnIn.pack(side=LEFT)
        #------- frmIn ----------#

        #------- frmOut ----------#
        self.frmOut = Frame(parent, bd=5)
        self.frmOut.pack()

        self.lblOut = Label(self.frmOut, text='Midi Output File Path', width=20)
        self.lblOut.pack(side=LEFT)	

        self.outFilePath = StringVar()
        self.entOut = Entry(self.frmOut, width=20, textvariable=self.outFilePath)
        self.entOut.pack(side=LEFT)	

        self.btnOut = Button(self.frmOut, text='Browse', command=self.btnOutBrowseClick)
        self.btnOut.pack(side=LEFT)
        #------- frmOut ----------#

        sep = Frame(parent, width=1, bd=5, bg='black')
        sep.pack(fill=X, expand=1)

        #------- frmButtons ----------#
        self.frmOut = Frame(parent, bd=5)
        self.frmOut.pack()

        self.btnConvert = Button(self.frmOut, text='Convert', command=self.btnConvertClick)
        self.btnConvert.pack()	

    #------- handle commands ----------#
    def selRadio(self):
        self.lblIn.config(text = self.inChoices[self.varRadio.get()] + ' Input File Path')
        self.lblOut.config(text = self.inChoices[(self.varRadio.get()+1)%2] + ' Output File Path')
        print str(self.varRadio.get())

    def btnInBrowseClick(self):
        rFilepath = askopenfilename(defaultextension='*',
            initialdir='.', initialfile='', parent=self.frmIn, title='select a file')
        self.inFilePath.set(rFilepath)
        print self.entIn.get()

    def btnOutBrowseClick(self):
        rFilepath = asksaveasfilename(defaultextension='*',
            initialdir='.', initialfile='', parent=self.frmIn, title='select a file')
        self.outFilePath.set(rFilepath)
        print self.entOut.get()

    def btnConvertClick(self):
        #defClr = self.btnConvert.cget("bg")
        self.btnConvert.config(relief=SUNKEN)
        self.btnConvert.update()
        #print 'Convert from %s to %s' % (self.inChoices[self.varRadio.get()], self.inChoices[(self.varRadio.get()+1)%2])
        print 'self.varRadio.get()', self.varRadio.get()

        if self.varRadio.get() == 0:
            inputTextFilePath = str(self.inFilePath.get()); outputMidiFilePath = str(self.outFilePath.get())
            print 'midi 4 txt', inputTextFilePath, outputMidiFilePath
            midi24txt.mid4txt(inputTextFilePath, outputMidiFilePath)
        else:
            inputMidiFilePath = str(self.inFilePath.get()); outputTextFilePath = str(self.outFilePath.get())
            print 'midi 2 txt', inputMidiFilePath, outputTextFilePath
            midi24txt.mid2txt(inputMidiFilePath, outputTextFilePath)
        time.sleep(0.5)
        self.btnConvert.config(relief=RAISED)
        self.btnConvert.update()

root = Tk()
root.title("Convert between Midi and Text Files")
#http://infohost.nmt.edu/tcc/help/pubs/tkinter/std-attrs.html#geometry
#http://infohost.nmt.edu/tcc/help/pubs/tkinter/toplevel.html
root.geometry("350x200+10+10")
gui = TheGui(root)
root.mainloop()

cgi

#!/usr/bin/env python
# from: http://webpython.codepoint.net/cgi_file_upload
import cgi, os
import cgitb; cgitb.enable()

try: # Windows needs stdio set for binary mode.
    import msvcrt
    msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
    msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
    pass

form = cgi.FieldStorage()

def upload():
    """ upload the file into files/ """
    fileitem = form['file']

    # Test if the file was uploaded
    if fileitem.filename:

       # strip leading path from file name to avoid
       #    directory traversal attacks
       fn = os.path.basename(fileitem.filename)
       open('files/' + fn, 'wb').write(fileitem.file.read())
       message = 'The file "' + fn +
               '" was uploaded successfully'

    else:
       message = 'No file was uploaded'

    print """\
    Content-Type: text/html\n

%s

    """ % (message,)

def main():
    #cgi.test()
    message = 'from main'
    for k in form.keys():
        if k != 'file':
            message = ''.join([message,
                k+': '+form.getvalue(k)+''])
     print """\
    Content-Type: text/html\n

%s

    """ % (message,)

main()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s