python常用工具代碼

m2yy 9年前發布 | 3K 次閱讀 Python

1.生成隨機數

      import random    #這個是注釋,引入模塊

      rnd = random.randint(1,500)#生成1-500之間的隨機數



2.讀文件

     f = open("c:\\1.txt","r")

     lines = f.readlines()#讀取全部內容

     for line in lines

             print line

3.寫文件

    f = open("c:\\1.txt","r+")#可讀可寫模式

    f.write("123")#寫入字符串



4.正則表達式,讀取tomcat的日志并打印日期

 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#由于是測試,只分析十行

          i=i+1

 f.close();



5.連接數據庫

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處理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模塊標準的是Tkinter,也有QT和MFC的模塊,有興趣的大家自己搜索下

    import Tkinter



    root=Tkinter.Tk()



    my=Label(root,"Welcome to python's world")



    my.pack()



    root.mainloop()


</pre>

 本文由用戶 m2yy 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!