mkaz.com home photography web dev about

My Python Notes

Marcus Kazmierczak, marcus@mkaz.com
Created On: July 29, 2004
Last Updated: August 14, 2005

Table of Contents


Introduction

Here are my notes for programming in Python. Lately, I've found using Python as a more rewarding and friendly language then Perl, which is where I have a lot of experience. Python is nice especially for co-development and maintaining code down-the-line. Python code tends to be a little less cryptic since there is usually only one way of doing things; which is definitely not the Perl way. To be honest though, I can still do anything in Perl faster.

If you are really into these holy wars you can read about the great Python -vs- Perl debate here, here and even here. But as some one who just wants to do some work and stop wasting time. Who cares, pick a language and Just Code Baby™.


List Data Structures

Names: Lists, Arrays, Tuples, (Strings). A tuple is a list that can't be changed; so append and delete do not work on tuples.

Create Empty List:

mylist = []

Create Shopping List:

mylist = ['apples', 'bananas', 'oranges']

Print List Item:

print mylist[0]
>> apples

Append to List:

mylist.append('coffee')

Delete from List:

del mylist['coffee']

Size of List:

size = len(mylist)

Dict Data Structures

Names: Dictionaries, Dicts, Hash, Associative Array

Create Empty Dict:

mydict = {}

Create Address Dict:

mydict = {
    'firstname': 'Marcus',
    'lastname': 'Kazmierczak',
    'e-mail': 'marcus@mkaz.com'}
NOTE: That can all be on one line if you like

Print Dict Item:

print mydict['firstname']
>> Marcus

Delete from Dict:

del mydict['firstname']

Size of Dict:

size = len(mydict)

List Dict Keys:

mydict.keys()
>> ['firstname', 'lastname', 'e-mail']

Sets Data Structures

Python 2.3 introduced sets as another data structure, which have the same mathematical set properties: union, intersection, etc...

import sets

Create Sets:

set1 = sets.Set(['apple','orange','banana'])
set2 = sets.Set(['blue','red','orange','green'])

Union Sets:

set1.union(set2)
>> Set(['blue', 'green', 'apple', 'orange', 'banana', 'red'])

# shortcut operator
set1 | set2

Intersection Sets:

set1.intersection(set2)
>> Set(['orange'])

# shortcut operator
set1 & set2

Difference Sets:

set1.difference(set2)
>> Set(['apple', 'banana'])

set2.difference(set1)
>> Set(['blue', 'green', 'red'])

Sym Difference:

set1.symmetric_difference(set2)
>> Set(['blue', 'green', 'apple', 'red', 'banana'])

Check if Element in Set:

'apple' in set1

Working with Files

Read Lines from File

filename = "files.txt"
f = open(filename, 'r')
lines = f.readlines();
for line in lines:
     print line
f.close()


Check if File/Directory Exists, similar to Perl's -e checks
Use the os module, see the full documentation at http://python.org/doc/current/lib/module-os.path.html

import os

file = "/my/file/path/name"

if os.path.exists(file):
    print "%s exists" % file

# here are some other things you can check for
if os.path.isabs(file):
    print "%s is absolute path" % file

if os.path.isdir(file):
    print "%s is directory" % file

if os.path.isfile(file):
    print "%s is file " % file

if os.path.islink(file):
    print "%s is link" % file

if os.path.ismount(file):
    print "%s is a mount point" % file

Grab a list of files in directory, similar to Perl's glob

dir = "/my/dir"

files = os.listdir(dir)
for file in files:
    print file

# or if you only want *.py
for file in os.listdir(dir):
    if (file.endswith(".py")):
        print file

# or if you want all files the start with 'test'
for file in os.listdir(dir):
    if (file.startswith("test")):
        print file
Misc Snippets

Read User Input from STDIN, Prompt User

cont = raw_input("Continue [Y/n]? ")

It's nice to strip out any whitespace and the newline, this can be done in one line:

cont = raw_input("Continue [Y/n]? ").strip()


Read Data in from STDIN

data = sys.stdin.read()

Full Examples


Related Links

Learning Python
by Mark Lutz; Paperback; Buy New: $23.77

Buy now from Amazon.com

Python Cookbook
Alex Martelli; Paperback; Buy New: $27.17

Buy now from Amazon.com