常用python編程模板匯總
在我們編程時,有一些代碼是固定的,例如Socket連接的代碼,讀取文件內(nèi)容的代碼,一般情況下我都是到網(wǎng)上搜一下然后直接粘貼下來改一改,當(dāng)然如果你能自己記住所有的代碼那更厲害,但是自己寫畢竟不如粘貼來的快,而且自己寫的代碼還要測試,而一段經(jīng)過測試的代碼則可以多次使用,所以這里我就自己總結(jié)了一下python中常用的編程模板,如果還有哪些漏掉了請大家及時補(bǔ)充哈。
一、讀寫文件
1、讀文件
(1)、一次性讀取全部內(nèi)容
filepath='D:/data.txt' #文件路徑 with open(filepath, 'r') as f: print f.read()
(2)讀取固定字節(jié)大小
# -*- 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)每次讀取一行
# -*- 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)一次讀取所有的行
# -*- 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、寫文件
# -*- coding: UTF-8 -*-
filepath='D:/data1.txt' #文件路徑
with open(filepath, "w") as f: #w會覆蓋原來的文件,a會在文件末尾追加
f.write('1234')
二、連接Mysql數(shù)據(jù)庫
1、連接
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
DB_URL='localhost'
USER_NAME='root'
PASSWD='1234'
DB_NAME='test'
# 打開數(shù)據(jù)庫連接
db = MySQLdb.connect(DB_URL,USER_NAME,PASSWD,DB_NAME)
# 使用cursor()方法獲取操作游標(biāo)
cursor = db.cursor()
# 使用execute方法執(zhí)行SQL語句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法獲取一條數(shù)據(jù)庫。
data = cursor.fetchone()
print "Database version : %s " % data
# 關(guān)閉數(shù)據(jù)庫連接
db.close()
2、創(chuàng)建表
#!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb # 打開數(shù)據(jù)庫連接 db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # 如果數(shù)據(jù)表已經(jīng)存在使用 execute() 方法刪除表。 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # 創(chuàng)建數(shù)據(jù)表SQL語句 sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )""" cursor.execute(sql) # 關(guān)閉數(shù)據(jù)庫連接 db.close()
3、插入
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打開數(shù)據(jù)庫連接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標(biāo)
cursor = db.cursor()
# SQL 插入語句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# 執(zhí)行sql語句
cursor.execute(sql)
# 提交到數(shù)據(jù)庫執(zhí)行
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# 關(guān)閉數(shù)據(jù)庫連接
db.close()
4、查詢
#!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb # 打開數(shù)據(jù)庫連接 db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 查詢語句 sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > '%d'" % (1000) try: # 執(zhí)行SQL語句 cursor.execute(sql) # 獲取所有記錄列表 results = cursor.fetchall() for row in results: fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] # 打印結(jié)果 print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \ (fname, lname, age, sex, income ) except: print "Error: unable to fecth data" # 關(guān)閉數(shù)據(jù)庫連接 db.close()
5、更新
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打開數(shù)據(jù)庫連接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標(biāo)
cursor = db.cursor()
# SQL 更新語句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
WHERE SEX = '%c'" % ('M')
try:
# 執(zhí)行SQL語句
cursor.execute(sql)
# 提交到數(shù)據(jù)庫執(zhí)行
db.commit()
except:
# 發(fā)生錯誤時回滾
db.rollback()
# 關(guān)閉數(shù)據(jù)庫連接
db.close()
三、Socket
1、服務(wù)器
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()
break
tcpSerSock.close()
2、客戶端
from socket import *
HOST = 'localhost'
PORT = 21568
BUFSIZ = 1024
ADDR = (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 data
except:
tcpCliSock.close()
四、多線程
import time, threading
# 新線程執(zhí)行的代碼:
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
還請大家積極補(bǔ)充!
相關(guān)文章
Python制作簡易聊天器,搭建UDP網(wǎng)絡(luò)通信模型
這篇文章主要介紹了Python制作簡易聊天器,搭建UDP網(wǎng)絡(luò)通信模型,用UDP建立網(wǎng)絡(luò)模型來完成一個簡單的聊天器,感興趣的小伙伴可以參考一下,希望對你有所幫助2022-01-01
詳解Python進(jìn)行數(shù)據(jù)相關(guān)性分析的三種方式
相關(guān)系數(shù)量化數(shù)據(jù)集的變量或特征之間的關(guān)聯(lián)。這些統(tǒng)計數(shù)據(jù)對科學(xué)和技術(shù)非常重要,Python?有很好的工具可以用來計算它們。SciPy、NumPy?和Pandas相關(guān)方法以及數(shù)據(jù)可視化功能,感興趣的可以了解一下2022-04-04
基于python分析你的上網(wǎng)行為 看看你平時上網(wǎng)都在干嘛
這篇文章主要介紹了基于python分析你的上網(wǎng)行為 看看你平時上網(wǎng)都在干嘛,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08
解決Python paramiko 模塊遠(yuǎn)程執(zhí)行ssh 命令 nohup 不生效的問題
這篇文章主要介紹了解決Python paramiko 模塊遠(yuǎn)程執(zhí)行ssh 命令 nohup 不生效的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
Pygame游戲開發(fā)之太空射擊實戰(zhàn)子彈與碰撞處理篇
相信大多數(shù)8090后都玩過太空射擊游戲,在過去游戲不多的年代太空射擊自然屬于經(jīng)典好玩的一款了,今天我們來自己動手實現(xiàn)它,在編寫學(xué)習(xí)中回顧過往展望未來,下面開始講解子彈與碰撞處理,在本課中,我們將添加玩家與敵人之間的碰撞,以及添加供玩家射擊的子彈2022-08-08
Python獲取網(wǎng)絡(luò)圖片和視頻的示例代碼
Python 是一種多用途語言,廣泛用于腳本編寫。我們可以編寫Python 腳本來自動化日常事務(wù)。本文將用Python實現(xiàn)獲取Google圖片和YouTube視頻,需要的可以參考一下2022-03-03

