Python: Method order

*NOTE: def() method/function must be defined before it is called. If the def is below where it is called will get a ‘NameError: name ‘donkey’ is not defined’

def donkey():

print “hello”


Python: Return a list or dictionary from a method

def mylist(a):
return fruit

print b

Get zipfile contents info. python.

import zipfile

for x in a.namelist():
...     if x.endswith('.zip'):
...             info=a.getinfo(x)
...             print "%s %s" % (info.filename, info.file_size)
... 4563  5435 8979

Find occurence of items in list.

letterDict = {}
all_letters_list =
test_string = “in mississippimississippimississippimississippi pigs can
fly like the wind”

# saving the dict
for letter in test_string:
letterDict[letter] = letterDict.get(letter, 0) + 1

print letterDict


print ‘-‘ * 60
print ‘Examine the line below to see how it worked ‘
print ‘ 1 – inserting:  letterDict[letter] = letterDict.get(letter, 0) +
1  – self initiates with value of 0 and increments +1’
print ‘ 2 –  reading :  letterDict.get(testLetter, 0)  – when reading –
insert a default count of 0 for those letters not found.’
print ‘-‘ * 60
print ‘test_string = ‘, test_string
print ‘letterDict = ‘, letterDict
print ‘Histogram (count) of letters in test string’

# reading the dict, but inserting default 0 for letters not found.
for testLetter in all_letters_list:
print ‘%s – %2s’ % (testLetter, letterDict.get(testLetter, 0))

Python: Get similar matching strings

import difflib
a("Phil Collins", ["Phil Colins","PhilCollins","Phil Collins","Phil Collins - Genesis"])

['Phil Collins', 'PhilCollins', 'Phil Colins']

Delete all empty directories in current path.

find -depth -type d -empty -exec rmdir {} ;

Resolving Drive that won't unmount.

# umount -f /dev/sdb1
umount: /dev/sdb1: device is busy
umount: /dev/sdb1: device is busy
# fuser -m /dev/sdb1
/dev/sdb1: 3322

(3322 is id of the process that uses the device. if you like to know what it is, you may try this:

# ps aux | grep 3322)

# kill -9 3322
# umount /dev/sdb1

Also dmsetup….just lvm mounts?

ls -lh /dev/mapper/
dmsetup remove_all

Creating and calling a class – python

Type "help", "copyright", "credits" or "license" for more information.
import Cfg #class you just created
c = Cfg.Cfg()

from Cfg import Cfg
c = Cfg()
bound method Cfg.test of <Cfg.Cfg instance at 0xb7ce35ec>>

Read text file with 'xeff' garbage data to utf-8

import codecs
fileObj =, “r”, “utf-8” )
u =
print u

Grab last element of a list/string

>>> path=’/donkey/file.cfg’
>>> var=path.split(‘/’)
>>> print var
[”, ‘donkey’, ‘file.cfg’]
>>> var[-1]

or can do


#note you must assign path.split(‘/’) to a string or path.string will
just print out the last letter of the 3rd element which is ‘g’