1. Generate Random Numbers
Import random #这个是注释, introducing modules
Rnd = Random.randint (1,500) #生成1-random number between 500
2. Read the file
f = open ("C:\\1.txt", "R")
lines = F.readlines () #读取全部内容
For line in lines
Print Line
3. Writing files
f = open ("C:\\1.txt", "r+") #可读可写模式
F.write ("123") #写入字符串
4. Regular expressions, read the Tomcat log and print the date
Import re
REGX = "\d\d\d\d-\d\d-\d+"
f = open ("C:\stdout.log", "R")
i = 0
For STR in f.readlines ():
If Re.search (REGX,STR):
Response.Write (str+ "<br>")
If i>10:break# is tested, only 10 rows are analyzed
I=i+1
F.close ();
5. Connect to the database
Import Pgdb
conn = Pgdb.connect
(host= ' localhost ', databse= ' Qingfeng ', user= ' Qingfeng ', password= ' 123 ')
cur = conn.cursor ()
Cur.execute ("SELECT * FROM Dream")
Print Cur.rowcount
6.SAX processing xml:
Import string
From Xml.sax import Saxlib, saxexts
Class Quotationhandler (Saxlib. Handlerbase):
"" "Crude sax Extractor for QUOTATIONS.DTD document" ""
def __init__ (self):
Self.in_quote = 0
Self.thisquote = ' '
def startdocument (self):
print '---Begin Document---'
def startelement (self, Name, attrs):
If name = = ' Quotation ':
print ' Quotation: '
Self.in_quote = 1
Else
Self.thisquote = Self.thisquote + ' {'
def endElement (self, name):
If name = = ' Quotation ':
Print String.Join (String.Split (self.thisquote[:230)) + ' ... ',
print ' (' +str (len (self.thisquote)) + ' bytes) \ n '
Self.thisquote = ' '
Self.in_quote = 0
Else
Self.thisquote = Self.thisquote + '} '
def characters (self, ch, start, length):
If Self.in_quote:
Self.thisquote = Self.thisquote + ch[start:start+length]
if __name__ = = ' __main__ ':
Parser = saxexts. Xmlparserfactory.make_parser ()
Handler = Quotationhandler ()
Parser.setdocumenthandler (Handler)
Parser.parsefile (Open ("Sample.xml"))
Parser.close ()
7.python GUI module Standard is Tkinter, also has Qt and MFC modules, interested in everyone's own search under
Import Tkinter
root=tkinter.tk ()
My=label (Root, "Welcome to Python's World")
My.pack ()
Root.mainloop ()
"Go" Python common tool code