Wednesday, June 24, 2009

python open and read through file

# open file 'r' for read only 
# this assumes that myfile.txt is 
#   in the current working directory  
theFile = open('myfile.txt', 'r')
 
# iterate through the lines in the file object 
for line in theFile:
    # this is where you would perform logic on each line, or just print 
    print line
 
# close the file 
theFile.close()
 
#output: 
# Line one is here 
# line two is here 
# line 3 is here! 
 

python - simple casting

# string to int 
a = int("22")
 
# string to float 
a = float("22")
 
# int to string 
a = str(22)
 
# int to float 
a = float(22)
 
#float to string 
a = str(22.0)
 
#float to int 
a = int(22.0)
 

python - basic database connection example with MySQLdb

 
# basic python connect to a mysql database 
import MySQLdb
 
# connect to db 
dbconnection = MySQLdb.connect(host="localhost", user="dbuser", passwd="dbpass", db="mydb")
dbcursor = dbconnection.cursor()
 
# create query 
sql = "select * from mytable" 
 
# execute query 
dbcursor.execute(sql)
 
# get query results 
results = dbcursor.fetchall()
 
# display results 
if len(results) == 0:
    print "there were no results." 
else:
    print "results:" 
    for item in results:
        print item
 
# clean up / close connection 
dbconnection.close()