Common Python Programming templates summary

Source: Internet
Author: User
In our programming, some code is fixed, such as the code of the socket connection, read the code of the contents of the file, in general I would like to search the Internet and then paste it directly down to change, of course, if you can remember all the code that is more powerful, but their own writing after all is not as fast as pasting, And the code you write to test, and a test of code can be used multiple times, so here I summed up the python commonly used programming templates, if there are still missing out please fill in time.

I. Read and write files

1. Read the file

(1), read all the contents at once

Filepath= ' D:/data.txt ' #文件路径with open (filepath, ' R ') as F:  print F.read ()

(2) Read fixed byte size

#-*-Coding:utf-8-*-filepath= ' d:/data.txt ' #文件路径f = open (filepath, ' R ') content= "" Try: While  True:    chunk = f.re AD (8)    if not chunk:      break    content+=chunkfinally:  f.close ()  print content

(3) read one line at a time

#-*-Coding:utf-8-*-filepath= ' d:/data.txt ' #文件路径f = open (filepath, "R") content= "" Try: While  True: line    = F.rea Dline ()    If not line:      break    content+=linefinally:  f.close ()  print content

(4) Read all rows at once

#-*-Coding:utf-8-*-filepath= ' d:/data.txt ' #文件路径with open (filepath, "R") as F:  txt_list = F.readlines () for i in TXT _list:  Print I,

2. Write files

#-*-Coding:utf-8-*-filepath= ' d:/data1.txt ' #文件路径with open (filepath, "w") as F: #w会覆盖原来的文件, A will append f.write at the end of the file  (' 1234 ')

Second, connect MySQL database

1. Connection

#!/usr/bin/python#-*-coding:utf-8-*-import mysqldbdb_url= ' localhost ' user_name= ' root ' passwd= ' 1234 ' DB_NAME= ' test ' # Open Database Connection DB = MySQLdb.connect (db_url,user_name,passwd,db_name) # Use the cursor () method to get an operation cursor = Db.cursor () # Use the Execute method to execute the SQL statement cursor.execute ("Select VERSION ()") # Use the Fetchone () method to get a database. data = Cursor.fetchone () print "Database version:%s"% data# close connection db.close ()

2. Create a table

#!/usr/bin/python#-*-coding:utf-8-*-import mysqldb# Open database Connection db = MySQLdb.connect ("localhost", "testuser", "test123", " TESTDB ") # Use the cursor () method to get the cursor = Db.cursor () # If the data table already exists using the Execute () method to delete the table. Cursor.execute ("DROP table IF EXISTS EMPLOYEE") # Create Data table SQL statement sql = "" CREATE Table EMPLOYEE ( first_name CHAR () not NU LL, last_name char (+), age INT, SEX CHAR (1), INCOME FLOAT) "" "Cursor.execute (SQL) # Close database connection Db.close ( )

3. Insert

#!/usr/bin/python#-*-coding:utf-8-*-import mysqldb# Open database Connection db = MySQLdb.connect ("localhost", "testuser", "test123", " TESTDB ") # Use the cursor () method to get the cursor = db.cursor () # SQL INSERT statement sql =" "INSERT into EMPLOYEE (first_name,     last_name, age, SEX, INCOME)     VALUES (' Mac ', ' Mohan ', ' M ', ' + ') ' "" "Try:  # Execute SQL statement  cursor.execute (SQL)  # commit to Database execution  Db.commit () except:  # Rollback In case there was any error  Db.rollback () # Close database connection Db.close ()

4. Enquiry

#!/usr/bin/python#-*-coding:utf-8-*-import mysqldb# Open database Connection db = MySQLdb.connect ("localhost", "testuser", "test123", " TESTDB ") # Use the cursor () method to get the cursor = db.cursor () # SQL query Statement sql =" SELECT * from EMPLOYEE \ WHERE INCOME > '%d ' "% Try: # Execute SQL statement cursor.execute (SQL) # get all records list results = Cursor.fetchall () for row in Results: fname = row[0] lname = row[1] Age = row[2] sex = row[3] income = row[4] # Print Results PR int "fname=%s,lname=%s,age=%d,sex=%s,income=%d"% \ (fname, lname, age, sex, income) except: print "Error: Unable to fecth data "# Close database connection Db.close ()

5. Update

#!/usr/bin/python#-*-coding:utf-8-*-import mysqldb# Open database Connection db = MySQLdb.connect ("localhost", "testuser", "test123", "  TESTDB ") # Use the cursor () method to get the cursor = db.cursor () # SQL UPDATE statement sql =" Update EMPLOYEE SET age = age + 1             WHERE SEX = '%c ' " % (' M ') Try:  # Execute SQL statement  cursor.execute (SQL)  # Commit to Database Execution  db.commit () except:  # Rollback When  an error occurs Db.rollback () # Close database connection Db.close ()

Third, Socket

1. Server

From socket import *from time Import ctimehost = "Port = 21568BUFSIZ = 1024ADDR = (HOST, PORT) Tcpsersock = socket (af_inet , Sock_stream) Tcpsersock.bind (ADDR) Tcpsersock.listen (5) while True:  print ' Waiting for connection ... '  Tcpclisock, addr = tcpsersock.accept ()   print ' ... connected from: ', addr while  True:    try:      data = TCPCLISOCK.RECV (bufsiz)       print ' < ', data      tcpclisock.send (' [%s]%s '% (CTime (), data))     except:      print ' Disconnect from: ', addr      tcpclisock.close ()       breaktcpsersock.close ()

2, the Client

From socket import *host = ' localhost ' PORT = 21568BUFSIZ = 1024ADDR = (HOST, PORT) Tcpclisock = socket (Af_inet, Sock_stream ) Tcpclisock.connect (ADDR) Try: While  True:    data = raw_input (' > ')    if data = = ' close ': Break    If Not data:      continue    tcpclisock.send (data)     data = Tcpclisock.recv (bufsiz)     print dataexcept:  

Four, multi-threaded

Import time, threading# code executed by the new thread: Def loop ():  print ' thread%s is running ... '% threading.current_thread (). Name  n = 0  while n < 5:    n = n + 1    print ' thread%s >>>%s '% (Threading.current_thread (). Name, N)    time.sleep (1)  print ' thread%s ended. '% Threading.current_thread (). Nameprint ' thread%s is running ... '% th Reading.current_thread (). Namet = Threading. Thread (Target=loop, name= ' Loopthread ') T.start () t.join () print ' thread%s ended. '% Threading.current_thread (). Name

We also invite you to actively add!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.