Thursday, 11 November 2010

Python Reference

#import libraries
import sys,os,shutil,glob,string,re,datetime
 
#=====================================
# IO Samples
#=====================================
 
#read file line by line
f=open('text.txt','r')
for line in f:
	print string.split(line, '\n')[0] #remove linebreak
 	
#read file all at once
f=open('text.txt','r')
text = f.read()		
print(text)
 
#current directory
print os.getcwd()
 
#list files/folders in current directory
for file in os.listdir(os.getcwd()):
	print file
	
#print directory structure
def printDir(path,indent):
	for root, dirs, files in os.walk(path):
		for name in dirs:
			print indent+name
			printDir(os.path.join(root,name),indent+" ")
		for name in files:
			print indent+name
	 
printDir(os.getcwd())	
	 
#create dir
os.mkdir("Test")
 
#delete dir
os.remove("Test")	
 
#execute command
os.system("mkdir x")
  
#execute command line and return a result
result = os.popen("ls").read()
  
#wildcard file names
print glob.glob("*.py")
  
#copy file
shutil.copy("file1.py","file2.py")
  
#movw file
shutil.move('dir1', 'dir2')
  
#command line arguments
print sys.argv
print sys.argv[1]
  
 
#=====================================
# Exception Handling
#=====================================
 
#catch error
try:
	f=open('test.py',r)
	f.readline()
except:
	print "Error:",sys.exc_info()
	print " Error:",sys.exc_info()[0]
	print " Msg  :",sys.exc_info()[1]	
 
#raise error	
try:
	raise NameError, 'Custom Error'
except:
	print "Error:",sys.exc_info()
  
 
#=====================================	
# String/Formatting Samples
#=====================================
 
#string character manipulation
sampletext = "Hello"
print sampletext[2:] #llo (everything but first 2)
print sampletext[-2:] #ll (last 2)
print sampletext #He (first 2)
print sampletext[:-2] #Hel (everything but last 2)
 
#templating string
t = string.Template("This $one is a $two")
print t.substitute(one='1',two='2')
 
#template from file
f=open('template.txt','r')
t = string.Template(f.read())
print t.substitute(param1='1',param2='2')
 
#split string
for resultline in result.split("\n"):	
	print resultline
 
#cast int to string
number = 1
text = str(number)
print text
 
 
#=====================================	
# DateTime Parsing/Formatting
#=====================================
#date
print datetime.date.today()
 
#datetime
print datetime.datetime.today()
 
#format date
print datetime.datetime.today().strftime("%y%m%d_%H%M%S")
 
#parse date
dt = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
print dt	
  
 	
#=====================================
# Math
#=====================================
val = 5
print '5 mod 2: ', val % 2
print '5 div 2: ', val / 2
 
print abs(-4)	
  
   
#=====================================	
# Regex
#=====================================
 
#regex
regexValue = "Name John"
regex = "(Name)\s*(?P<FirstName>\w+)"
m = re.match(regex,regexValue)	
if m:
 print 'First Name: ' + m.group('FirstName')
else:
 print 'FirstName not found'
 
 
#=====================================
# Custom Libraries/Modules
#=====================================
 
# Save this module to fibo.py (Fibonacci numbers)
#-------------
# write Fibonacci series up to n
def fib(n):
    a, b = 0, 1
    while b < n:
        print b,
        a, b = b, a+b
 
# return Fibonacci series up to n
def fib2(n): 
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result
#-------------
 
# Calling fib methods
import fibo
s = 'This is fibo or 5: ' + str(fibo.fib2(5))
print s	
 
# Save this module to cars.py
#-------------
# Custom class
class Car:	
	def __init__(self,i):
		self.i = i
 	
	def increment(self):
		print 'incrementing'
		self.i=self.i+1
		
	def printvalue(self):
		print self.i;
		
# Calling cars class
import cars
car = cars.Car(5)
print car.i
car.printvalue()
car.increment()
car.printvalue()	
 
 
#=====================================
# Unit Tests
#=====================================
 
import unittest
 
class TestStatisticalFunctions(unittest.TestCase):
	def test_average(self):
		self.assert_(isinstance(2 + 4, int))
		self.assertEqual(abs(-4), 4)        
		self.assertRaises(ZeroDivisionError, lambda : 1/0)        
 
#run tests		
unittest.main()

No comments:

Post a Comment