Python 常用代码片段,,一些比较常用的pytho
Python 常用代码片段,,一些比较常用的pytho
一些比较常用的python代码片段
1、生成随机数
import random #这个是注释,引入模块rnd = random.randint(1,500)#生成1-500之间的随机数
2、python读文件
f = open("c:\\1.txt","r")lines = f.readlines()#读取全部内容for line in lines print line
3、 python写文件
f = open("c:\\1.txt","r+")#可读可写模式f.write("123")#写入字符串
4、 正则表达式,读取tomcat的日志并打印日期
import reregx = "\d\d\d\d-\d\d-\d+"f = open("c:\stdout.log","r")i = 0for str in f.readlines(): if re.search(regx,str): Response.write(str+"<br>") if i>10:break#由于是测试,只分析十行 i=i+1f.close();
5、 连接数据库
import pgdbconn = pgdb.connect(host='localhost',databse='qingfeng',user='qingfeng',password='123')cur = conn.cursor() cur.execute("select * from dream") print cur.rowcount
6、 pythonSAX处理xml:
import stringfrom xml.sax import saxlib, saxextsclass 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模块标准的是Tkinter,也有QT和MFC的模块,有兴趣的大家自己搜索下
import Tkinterroot=Tkinter.Tk()my=Label(root,"Welcome to python's world")my.pack()root.mainloop()
相关内容
- python多线程Ping网段,python多线程ping,import sysim
- python实现选择排序算法,python排序算法,def ssort(V)
- python的依赖注入,python依赖注入,Sample Pytho
- python如何判断变量是否已经定义,python判断变量,Pytho
- 显示当前目录所有py文件的类名和函数名,当前目录p
- python yield关键字说明用法,pythonyield,yield 用法说明yi
- web.py上传图片并生成略缩图,web.py略缩图,生成略缩图时
- webpy 下载文件,webpy,webpy下载文件需要指
- python常见的字符串操作,python字符串,下面列出了常用的
- 在web.py的Controller方法中使用装饰器,web.pycontroller,imp
评论关闭