常用python编程模板汇总


Posted in Python onFebruary 12, 2016

在我们编程时,有一些代码是固定的,例如Socket连接的代码,读取文件内容的代码,一般情况下我都是到网上搜一下然后直接粘贴下来改一改,当然如果你能自己记住所有的代码那更厉害,但是自己写毕竟不如粘贴来的快,而且自己写的代码还要测试,而一段经过测试的代码则可以多次使用,所以这里我就自己总结了一下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)每次读取一行

# -*- 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 '<', 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

# 新线程执行的代码:
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

还请大家积极补充!

Python 相关文章推荐
python基础教程之类class定义使用方法
Feb 20 Python
使用Python生成XML的方法实例
Mar 21 Python
详解python之多进程和进程池(Processing库)
Jun 09 Python
CentOS7.3编译安装Python3.6.2的方法
Jan 22 Python
Python cookbook(数据结构与算法)字典相关计算问题示例
Feb 18 Python
Python3.4 tkinter,PIL图片转换
Jun 21 Python
对python中的argv和argc使用详解
Dec 15 Python
Python 从subprocess运行的子进程中实时获取输出的例子
Aug 14 Python
如何利用python生成MD5并去重
Dec 07 Python
如何用python绘制雷达图
Apr 24 Python
Python3中最常用的5种线程锁实例总结
Jul 07 Python
python装饰器代码解析
Mar 23 Python
python黑魔法之参数传递
Feb 12 #Python
python实现井字棋游戏
Mar 30 #Python
python搭建微信公众平台
Feb 09 #Python
Python实例一个类背后发生了什么
Feb 09 #Python
Python中的条件判断语句基础学习教程
Feb 07 #Python
Python模拟登录验证码(代码简单)
Feb 06 #Python
Python上传package到Pypi(代码简单)
Feb 06 #Python
You might like
php的控制语句
2006/10/09 PHP
用PHP中的 == 运算符进行字符串比较
2006/11/26 PHP
PHP提取字符串中的图片地址[正则表达式]
2011/11/12 PHP
php下拉选项的批量操作的实现代码
2013/10/14 PHP
ecshop适应在PHP7的修改方法解决报错的实现
2016/11/01 PHP
jQuery中绑定事件的命名空间详解
2011/04/05 Javascript
『jQuery』名称冲突使用noConflict方法解决
2013/04/22 Javascript
鼠标滚轴控制文本框值的JS代码
2013/11/19 Javascript
js实现可得到不同颜色值的颜色选择器实例
2015/02/28 Javascript
浅析JavaScript中的事件机制
2015/06/04 Javascript
js带点自动图片轮播幻灯片特效代码分享
2015/09/07 Javascript
简单解析JavaScript中的__proto__属性
2016/05/10 Javascript
jQuery基本选择器(实例及表单域value的获取方法)
2016/05/20 Javascript
AngularJS  双向数据绑定详解简单实例
2016/10/20 Javascript
Vue form 表单提交+ajax异步请求+分页效果
2017/04/22 Javascript
VUE2.0+Element-UI+Echarts封装的组件实例
2018/03/02 Javascript
vue和webpack项目构建过程常用的npm命令详解
2018/06/15 Javascript
vue滚动插件better-scroll使用详解
2019/10/18 Javascript
vue 在服务器端直接修改请求的接口地址
2020/12/19 Vue.js
微信小程序实现下拉加载更多商品
2020/12/29 Javascript
安装ElasticSearch搜索工具并配置Python驱动的方法
2015/12/22 Python
Python简单遍历字典及删除元素的方法
2016/09/18 Python
python GUI库图形界面开发之PyQt5动态(可拖动控件大小)布局控件QSplitter详细使用方法与实例
2020/03/06 Python
CSS3盒子模型详解
2013/04/24 HTML / CSS
html5使用canvas画三角形
2014/12/15 HTML / CSS
森海塞尔美国官网:Sennheiser耳机与耳麦
2017/07/19 全球购物
欧舒丹加拿大官网:L’Occitane加拿大
2017/10/29 全球购物
美国滑板店:Tactics
2020/11/08 全球购物
中医药大学毕业生自荐信
2013/11/08 职场文书
党支部书记先进事迹
2014/01/17 职场文书
2014年服务行业工作总结
2014/11/18 职场文书
地震慰问信
2015/02/14 职场文书
求职自我评价范文
2015/03/09 职场文书
酒店仓管员岗位职责
2015/04/01 职场文书
MySQL 表空间碎片的概念及相关问题解决
2021/05/07 MySQL
使用JS前端技术实现静态图片局部流动效果
2022/08/05 Javascript