一般的なpythonプログラミングテンプレートの概要
一、ファイルの読み書き
1、ファイルを読む
(1)、全てを一括して読み取る
filepath='D:/data.txt' #
with open(filepath, 'r') as f:
print f.read()
(2)読み出し固定バイトサイズ
# -*- 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行ずつ読み込む
# -*- 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データベースへの接続
1、接続
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
DB_URL='localhost'
USER_NAME='root'
PASSWD='1234'
DB_NAME='test'
#
db = MySQLdb.connect(DB_URL,USER_NAME,PASSWD,DB_NAME)
# cursor()
cursor = db.cursor()
# execute SQL
cursor.execute("SELECT VERSION()")
# fetchone() 。
data = cursor.fetchone()
print "Database version : %s " % data
#
db.close()
2、表の作成
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
#
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# cursor()
cursor = db.cursor()
# execute() 。
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# 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)
#
db.close()
3、挿入
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
#
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# cursor()
cursor = db.cursor()
# SQL
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# sql
cursor.execute(sql)
#
db.commit()
except:
# Rollback in case there is any error
db.rollback()
#
db.close()
4、照会
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
#
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# cursor()
cursor = db.cursor()
# SQL
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# 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]
#
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"
#
db.close()
5、更新
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
#
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# cursor()
cursor = db.cursor()
# SQL
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
WHERE SEX = '%c'" % ('M')
try:
# SQL
cursor.execute(sql)
#
db.commit()
except:
#
db.rollback()
#
db.close()
三、Socket
1、サーバー
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 '
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
# :
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
皆さんも積極的に補充してください!