Summary of common python programming templates

Source: Internet
Author: User
This article mainly introduces common python programming templates and summarizes common Python programming templates. If you are interested, refer to some of the code that is fixed during our programming, for example, the Socket connection code, the code used to read the file content, I usually search for it online and paste it directly to change it, of course, if you can remember all the code by yourself, it is better to write it by yourself, but it is better to paste it quickly, and the code you write must be tested, A piece of tested code can be used multiple times, so I will summarize the commonly used programming templates in python here. If there are any omissions, please add them in time.

I. Read and Write files

1. Read files

(1) read all the content at a time

Filepath = 'd:/data.txt '# file path with open (filepath, 'R') as f: print f. read ()

(2) read fixed byte size

#-*-Coding: UTF-8-*-filepath = 'd:/data.txt '# file path f = open (filepath, 'R') content = "" try: while True: chunk = f. read (8) if not chunk: break content + = chunkfinally: f. close () print content

(3) read a row at a time

#-*-Coding: UTF-8-*-filepath = 'd:/data.txt '# file path f = open (filepath, "r") content = "try: while True: line = f. readline () if not line: break content + = linefinally: f. close () print content

(4) read all rows at a time

#-*-Coding: UTF-8-*-filepath = 'd:/data.txt '# file path 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 # file path with open (filepath, "w") as f: # w will overwrite the original file, and a will append f at the end of the file. write ('20140901 ')

2. Connect to the Mysql database

1. Connection

#! /Usr/bin/python #-*-coding: UTF-8-*-import MySQLdbDB_URL = 'localhost' USER _ NAME = 'root' PASSWD = '000000' DB _ NAME = 'test' # Open the database connection db = MySQLdb. connect (DB_URL, USER_NAME, PASSWD, DB_NAME) # Use the cursor () method to obtain the operation cursor = db. cursor () # Use execute to execute SQL sentence cursor.exe cute ("SELECT VERSION ()") # Use the fetchone () method to obtain a database. Data = cursor. fetchone () print "Database version: % s" % data # close Database connection db. close ()

2. Create a table

#! /Usr/bin/python #-*-coding: UTF-8-*-import MySQLdb # Open the database connection db = MySQLdb. connect ("localhost", "testuser", "test123", "TESTDB") # Use the cursor () method to obtain the operation cursor = db. cursor () # If the data table already exists, use the execute () method to delete the table. Cursor.exe cute ("drop table if exists employee") # CREATE a data table SQL statement SQL = "CREATE TABLE EMPLOYEE (FIRST_NAME CHAR (20) NOT NULL, LAST_NAME CHAR (20 ), age int, sex char (1), income float) "cursor.exe cute (SQL) # disable database connection to db. close ()

3. insert

#! /Usr/bin/python #-*-coding: UTF-8-*-import MySQLdb # Open the database connection db = MySQLdb. connect ("localhost", "testuser", "test123", "TESTDB") # Use the cursor () method to obtain the operation cursor = db. cursor () # SQL insert statement SQL = "INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('mac', 'mohan', 20, 'M', 2000) "" try: # execute the SQL statement cursor.exe cute (SQL) # submit it to the database to execute the db. commit () handle T: # Rollback in case there is any error db. rollback () # disable database connection to db. close ()

4. Query

#! /Usr/bin/python #-*-coding: UTF-8-*-import MySQLdb # Open the database connection db = MySQLdb. connect ("localhost", "testuser", "test123", "TESTDB") # Use the cursor () method to obtain the operation cursor = db. cursor () # SQL query statement SQL = "SELECT * from employee \ where income> '% d'" % (1000) try: # Run the SQL statement cursor.exe cute (SQL) # retrieve the list of all records results = cursor. fetchall () for row in results: fname = row [0] lname = row [1] age = row [2] sex = row [3] income = row [4] # print the result print "fname = % s, lname = % s, age = % d, sex = % s, income = % d "% \ (fname, lname, age, sex, income) failed T: print" Error: unable to fecth data "# disable database connection to db. close ()

5. Update

#! /Usr/bin/python #-*-coding: UTF-8-*-import MySQLdb # Open the database connection db = MySQLdb. connect ("localhost", "testuser", "test123", "TESTDB") # Use the cursor () method to obtain the operation cursor = db. cursor () # SQL update statement SQL = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '% C'" % ('M') try: # Run the SQL statement cursor.exe cute (SQL) # submit it to the database to execute the database. commit () commit T: # roll back the db when an error occurs. rollback () # disable database connection to db. close ()

Iii. Socket

1. Servers

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. 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:  tcpCliSock.close() 

4. Multithreading

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... '% threading. current_thread (). namet = threading. thread (target = loop, name = 'loopthread') t. start () t. join () print 'thread % s ended. '% threading. current_thread (). name

Please also make some suggestions!

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.