一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術(shù)及教程分享平臺(tái)!
分類導(dǎo)航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務(wù)器之家 - 腳本之家 - Python - 常用python編程模板匯總

常用python編程模板匯總

2020-08-12 09:16xingjiarong Python

這篇文章主要為大家詳細(xì)介紹了常用python編程模板,總結(jié)了Python編程常用模板,感興趣的朋友可以參考一下

在我們編程時(shí),有一些代碼是固定的,例如Socket連接的代碼,讀取文件內(nèi)容的代碼,一般情況下我都是到網(wǎng)上搜一下然后直接粘貼下來改一改,當(dāng)然如果你能自己記住所有的代碼那更厲害,但是自己寫畢竟不如粘貼來的快,而且自己寫的代碼還要測試,而一段經(jīng)過測試的代碼則可以多次使用,所以這里我就自己總結(jié)了一下python中常用的編程模板,如果還有哪些漏掉了請大家及時(shí)補(bǔ)充哈。

一、讀寫文件

1、讀文件

(1)、一次性讀取全部內(nèi)容

?
1
2
3
4
filepath='D:/data.txt' #文件路徑
 
with open(filepath, 'r') as f:
  print f.read()

(2)讀取固定字節(jié)大小

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# -*- 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)每次讀取一行

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# -*- 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)一次讀取所有的行

?
1
2
3
4
5
6
7
8
9
# -*- 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、寫文件

?
1
2
3
4
5
6
# -*- coding: UTF-8 -*-
 
filepath='D:/data1.txt' #文件路徑
 
with open(filepath, "w") as f: #w會(huì)覆蓋原來的文件,a會(huì)在文件末尾追加
  f.write('1234')

二、連接Mysql數(shù)據(jù)庫

1、連接

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/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)建表

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<p>#!/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()</p>

3、插入

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/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、查詢

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<p>#!/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()</p>

5、更新

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/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ā)生錯(cuò)誤時(shí)回滾
  db.rollback()
 
# 關(guān)閉數(shù)據(jù)庫連接
db.close()

三、Socket

1、服務(wù)器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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、客戶端

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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()

四、多線程

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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ǔ)充!

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产一区二区三区日韩 | 欧美一区二区三区大片 | 欧美成人aa | 精品国产自在在线在线观看 | 亚洲成人福利 | 亚洲国产欧美日韩在线一区 | ady@ady9.映画网| 久草高清在线 | 国产欧美日韩综合二区三区 | 免费日批软件 | 网友自拍偷拍 | 无套白浆| 人人爽人人香蕉 | 99成人国产精品视频 | 狠狠色综合久久久久尤物 | 日韩在线毛片 | 青苹果乐园影院在线播放 | 久久视频在线视频观看精品15 | 亚洲国产欧美在线看片 | 亚洲欧美综合区自拍另类 | 美女靠逼免费视频 | www.久久艹| 香蕉久草 | 狠狠色伊人亚洲综合网站色 | 青春娱乐国产分类精品二 | 精品一区二区三区五区六区 | 国产成人精品日本亚洲网站 | chinesezoozvideos | 免费网址在线观看入口推荐 | 蜜桃视频在线观看官网 | 免费高清视频在线观看 | 韩国三级做爰 | 美女班主任下面好爽好湿好紧 | chinaspanking调教 chanelpreston欧美网站 | 狠狠综合久久综合网站 | 91精品国产品国语在线不卡 | 人人福利| 99国产精品久久久久久久... | 无码射肉在线播放视频 | 毛片免费的| 亚洲成人在线播放 |