import random
rnd = random.randint(1, 500) # 1~500 整數
with open(r"c:\1.txt", "r") as f:
for line in f:
print(line.rstrip())
with open(r"c:\1.txt", "r+") as f:
f.write("123")
import re
regex = r"\d{4}-\d{2}-\d+"
with open(r"c:\stdout.log", "r") as f:
for i, line in enumerate(f):
if re.search(regex, line):
print(line.rstrip())
if i > 10: break
import pgdb
conn = pgdb.connect(host='localhost', database='qingfeng',
user='qingfeng', password='123')
cur = conn.cursor()
cur.execute("select * from dream")
print(cur.rowcount)
程式碼較長,請參考原文連結:JavaEye 討論串
import string
from xml.sax import saxlib, saxexts
class QuotationHandler(saxlib.HandlerBase):
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 += '{'
def endElement(self, name):
if name == 'quotation':
print(' '.join(string.split(self.thisquote[:230])) + '...',
f'({len(self.thisquote)} bytes)\n')
self.thisquote = ''
self.in_quote = 0
else:
self.thisquote += '}'
def characters(self, ch, start, length):
if self.in_quote:
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()
import Tkinter
root = Tkinter.Tk()
label = Tkinter.Label(root, text="Welcome to Python's world")
label.pack()
root.mainloop()
標準 GUI 庫為 Tkinter,亦可使用 PyQt/PySide (Qt) 或 wxPython。