Home / Python / Archive by category 'Language Basics'

Language Basics

Write xml file using python

from xml.dom.minidom import Document
doc = Document()
people = doc.createElement("people")
doc.appendChild(people)
aperson = doc.createElement("person")
people.appendChild(aperson)
name = doc.createElement("name")
aperson.appendChild(name)
personname = doc.createTextNode("Annie")
name.appendChild(personname)
filename = "people.xml"
f = open(filename, "w")
f.write(doc.toprettyxml(indent="   "))
f.close()

Read and display data from sqlite table using python

import cgi, os, sys
import sqlite3 as db
 
conn = db.connect('test.db')
cursor = conn.cursor()
conn.row_factory = db.Row
cursor.execute("select * from person")
rows = cursor.fetchall()
 
sys.stdout.write("Content-type: text.html\r\n\r\n")
sys.stdout.write("")
sys.stdout.write("<html><body><p>")
for row in rows:
   sys.stdout.write("%s %s %s" % (row[0],row[1],row[2]))
   sys.stdout.write("<br />")
sys.stdout.write("</p></body></html>")

Create a simple httpserver in python

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
 
Handler = SimpleHTTPRequestHandler
Server = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"
 
if sys.argv[1:]:
   port = int(sys.argv[1])
else:
   port = 8000
 
server_address = ('127.0.0.1', port)
 
Handler.protocol_version = Protocol
httpd = Server(server_address, Handler)
 
print("Serving HTTP")
httpd.serve_forever()

Website crawler in python

import urllib, htmllib, formatter, re, sys
 
url = sys.argv[1]
website = urllib.urlopen("http://"+url)
data = website.read()
website.close()
format = formatter.AbstractFormatter(formatter.NullWriter())
ptext = htmllib.HTMLParser(format)
ptext.feed(data)
links = []
links = ptext.anchorlist
for link in links:
   if re.search('http', link) != None:
      print(link)
      website = urllib.urlopen(link)
      data = website.read()
      website.close()
      ptext = htmllib.HTMLParser(format)
      ptext.feed(data)
      morelinks = ptext.anchorlist
      for alink in morelinks:
         if re.search('http', alink) != None:
            links.append(alink)

Get stock quote from yahoo finance in python

import urllib, re, sys
 
symbol = sys.argv[1]
url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(url+symbol).read()
m = re.search('span id="ref.*>(.*)<', content)
if m:
   quote = m.group(1)
else:
   quote = 'no quote for symbol: ' + symbol
print(quote)

Parse hyperlinks in webpage using python

import urllib, htmllib, formatter
 
website = urllib.urlopen("http://w3mentor.com")
data = website.read()
website.close()
format = formatter.AbstractFormatter(formatter.NullWriter())
ptext = htmllib.HTMLParser(format)
ptext.feed(data)
for link in ptext.anchorlist:
   print(link)

Parse html using htmllib in python

import htmllib, urllib, formatter, sys
 
website = urllib.urlopen("http://w3mentor.com")
data = website.read()
website.close()
format = formatter.AbstractFormatter(formatter.DumbWriter(sys.stdout))
ptext = htmllib.HTMLParser(format)
ptext.feed(data)
ptext.close()

Use nntplib to read news in python

from nntplib import *
s = NNTP('web.aioe.org')
(resp, count, first, last, name) = s.group('comp.lang.python')
(resp, subs) = s.xhdr('subject', (str(first)+'-'+str(last)))
for subject in subs[-10:]:
   print(subject)
number = input('Which article do you want to read? ')
(reply, num, id, list) = s.body(str(number))
for line in list:
   print(line)

Read gmail email using python imap

import imaplib
 
mailserver = imaplib.IMAP4_SSL('imap.gmail.com', 993)
username = 'gmailusername'
password = 'gmailpassword'
mailserver.login(username, password)
 
status, count = mailserver.select('Inbox')
status, data = mailserver.fetch(count[0], '(UID BODY[TEXT])')
 
print data[0][1]
 
mailserver.close()
mailserver.logout()

Send email using gmail smtp and python

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
 
fromaddr = 'fromaddr@gmail.com'
toaddr = 'toaddr@gmail.com'
text = 'test email message sent from Python code'
username = 'fromaddruser'
password = 'fromaddrpassword'
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = 'Test'
msg.attach(MIMEText(text))
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
server.sendmail(fromaddr, toaddr, msg.as_string())
server.quit()

FTP connect and login using Python ftplib

import ftplib
 
connect = ftplib.FTP("www.mysite.com")
connect.login("domain\user", "password")
data = []
connect.dir(data.append)
connect.quit()
for line in data:
   print(line)

CRUD operations in sqlite using python

import sqlite3 as db
 
conn = db.connect('mytest.db')
cursor = conn.cursor()
cursor.execute("drop table if exists datecounts")
cursor.execute("create table datecounts(date text, count int)")
cursor.execute('insert into datecounts values("12/1/2011",35)')
cursor.execute('insert into datecounts values("12/2/2011",42)')
cursor.execute('insert into datecounts values("12/3/2011",38)')
cursor.execute('insert into datecounts values("12/4/2011",41)')
cursor.execute('insert into datecounts values("12/5/2011",40)')
cursor.execute('insert into datecounts values("12/6/2011",28)')
cursor.execute('insert into datecounts values("12/7/2011",45)')
conn.row_factory = db.Row
cursor.execute("select * from datecounts")
rows = cursor.fetchall()
for row in rows:
   print("%s %s" % (row[0], row[1]))
cursor.execute("select avg(count) from datecounts")
row = cursor.fetchone()
print("The average count for the week was %s" % row[0])
cursor.execute("delete from datecounts where count = 40")
cursor.execute("select * from datecounts")
rows = cursor.fetchall()
for row in rows:
   print("%s %s" % (row[0], row[1]))

Query sqlite table using python

import sqlite3 as db
 
conn = db.connect('mytest.db')
conn.row_factory = db.Row
cursor = conn.cursor()
 
cursor.execute("select * from person")
rows = cursor.fetchall()
for row in rows:
   print("%s %s %s" % (row["name"], row["age"], row["address"]))
conn.close()

Insert values in sqlite table using python

import sqlite3 as db
 
conn = db.connect('mytest.db')
cursor = conn.cursor()
cursor.execute('insert into person values("Mani","23","22,2nd cross, ka")')
cursor.execute('insert into person values("Raja","22","5th cross, ka")')
conn.close()

create table in sqlite using python

import sqlite3 as db
 
conn = db.connect('mytest.db')
cursor = conn.cursor()
cursor.execute("create table person(name text, age text, address text)")
print("table created")

using shapes module in python

from shapes import Shape
from shapes import Rectangle
 
s1 = Shape(2,4)
print(s1)
r1 = Rectangle(4,8,3,5)
print(r1)

convert temperature using tempconv in python

from tempconv import ctof
from tempconv import ftoc
 
temp = 95
convTemp = ftoc(temp)
print("the converted temp is " + str(convTemp))
temp = 0
convTemp = ctof(temp)
print("the converted temp is " + str(convTemp))

Define class with methods and invoke them in python

class Person:
   def __init__(self, first, middle, last, age):
      self.first = first;
      self.middle = middle;
      self.last = last;
      self.age = age;
 
   def __str__(self):
      return self.first + ' ' + self.middle + ' ' + self.last + \
        ' ' + str(self.age)
 
   def initials(self):
      return self.first[0] + self.middle[0] + self.last[0]
 
   def changeAge(self, val):
      self.age += val
 
myPerson = Person('Raja', 'I', 'Kumar', 21)
print(myPerson)
myPerson.changeAge(5)
print(myPerson)
print(myPerson.initials())

simple function example in python

def convertTemp(temp, scale):
   if scale == "c":
      return (temp - 32.0) * (5.0/9.0)
   elif scale == "f":
      return temp * 9.0/5.0 + 32
 
temp = int(input("Enter a temperature: "))
scale = input("Enter the scale to convert to: ")
converted = convertTemp(temp, scale)
print("The converted temp is: " + str(converted))

For loop over string array in python

for name in ["kak", "John", "Mani", "Matt"]:
   print(name)