When we are programming, some of the code is fixed, such as socket connection code, read the file contents of the code, generally I will search the Internet and then directly paste down to change, of course, if you can remember all the code that more powerful, but their own writing is not as fast as pasting, and write their own code to test, and a test of the code can be used many times, so here I summed up a few of the common programming templates in Python, if there are any missing and please be timely to add ha.
I. Read and write documents
1, read the file
(1), read all content 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.read (8)
if not chunk:
break
content+=chunk
finally:
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.readline ()
if not line: Break
Content+=line
finally:
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 the document
#-*-Coding:utf-8-*-
filepath= ' d:/data1.txt ' #文件路径 with
open (filepath, "w") as F: #w会覆盖原来的文件, A will append at the end of the file
f.write (' 1234 ')
Second, the connection MySQL database
1, Connection
#!/usr/bin/python
#-*-coding:utf-8-*-import mysqldb db_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
the action cursor 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 DB 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 action cursor
cursor = db.cursor ()
# If the datasheet already exists use the Execute () method to delete the table.
cursor.execute ("DROP TABLE IF EXISTS employee")
# Create datasheet SQL statement sql = "" Create
Table EMPLOYEE (
first_ NAME Char not NULL,
last_name char (m), 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 Cursor () method to get action cursor
cursor = db.cursor ()
# SQL INSERT statement
sql = '" ' Insert Into the EMPLOYEE (first_name,
last_name, age, SEX, income)
VALUES (' Mac ', ' Mohan ', ', ', ' M ', Watts) "" "
Try:
# Execute SQL statement
cursor.execute (SQL)
# Commit to Database Execution
db.commit ()
except:
# Rollback in case there Are any error
Db.rollback ()
# Close database connection
db.close ()
4, Inquiry
#!/usr/bin/python
#-*-coding:utf-8-*-
import mysqldb
# Open database connection
db = MySQLdb.connect ("localhost", " TestUser "," test123 "," TestDB ")
# Use Cursor () method to get action cursor
cursor = db.cursor ()
# SQL query statement
sql = ' SELECT * FROM EMPLOYEE \
WHERE income > '%d '% (1000)
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 the result print
"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 Cursor () method to get action cursor
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 C13/>db.commit ()
except:
# rollback Db.rollback () # When an error occurs (
)
# Close database connection
db.close ()
Third, Socket
1, Server
From socket import * from time
import ctime
HOST = '
PORT = 21568
bufsiz = 1024
ADDR = (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 ()
Tcpsersock.close ()
2. Client
From socket import *
HOST = ' localhost '
PORT = 21568
bufsiz = 1024
ADDR = (HOST, PORT)
Tcpclisock = Cket (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 Data
except:
Four, multithreading
Import time, Threading
# code for new thread execution:
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 (). Name
print ' thread%s is running ... ' % Threading.current_thread (). Name
t = Threading. Thread (Target=loop, name= ' Loopthread ')
T.start ()
t.join ()
print ' thread%s ended. '% Threading.current_thread (). Name
Reprint: http://blog.csdn.net/xingjiarong/article/details/50651235