常用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的Flask框架中web表单的教程
Apr 20 Python
浅析Python多线程下的变量问题
Apr 28 Python
详解Python程序与服务器连接的WSGI接口
Apr 29 Python
Python django实现简单的邮件系统发送邮件功能
Jul 14 Python
解决pycharm运行出错,代码正确结果不显示的问题
Nov 30 Python
windows上安装python3教程以及环境变量配置详解
Jul 18 Python
详解Python打包分发工具setuptools
Aug 05 Python
pandas中的数据去重处理的实现方法
Feb 10 Python
python利用线程实现多任务
Sep 18 Python
Python生成pdf目录书签的实例方法
Oct 29 Python
Python实现Word文档转换Markdown的示例
Dec 22 Python
将Python代码打包成.exe可执行文件的完整步骤
May 12 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
wordpress之wp-settings.php
2007/08/17 PHP
php异常处理方法实例汇总
2015/06/24 PHP
php算法实例分享
2015/07/14 PHP
php用户登录之cookie信息安全分析
2016/05/13 PHP
thinkphp隐藏index.php/home并允许访问其他模块的实现方法
2016/10/13 PHP
PHP使用mysqli同时执行多条sql查询语句的实例
2019/03/22 PHP
JQUERY操作JSON实例代码
2010/02/09 Javascript
从盛大通行证上摘下来的身份证验证js代码
2011/01/11 Javascript
JqGrid web打印实现代码
2011/05/31 Javascript
使用javascript实现Iframe自适应高度
2014/12/24 Javascript
2014 年最热门的21款JavaScript框架推荐
2014/12/25 Javascript
前端设计师们最常用的JS代码汇总
2016/09/25 Javascript
浅谈jQuery操作类数组的工具方法
2016/12/23 Javascript
js实现三级联动效果(简单易懂)
2017/03/27 Javascript
前端构建工具之gulp的语法教程
2017/06/12 Javascript
Vue中的vue-resource示例详解
2018/11/02 Javascript
jQuery实现动态生成年月日级联下拉列表示例
2019/05/11 jQuery
JS数组属性去重并校验重复数据
2020/01/10 Javascript
跟老齐学Python之赋值,简单也不简单
2014/09/24 Python
Python中list初始化方法示例
2016/09/18 Python
如何在Django中设置定时任务的方法示例
2019/01/18 Python
python内存动态分配过程详解
2019/07/15 Python
python SVM 线性分类模型的实现
2019/07/19 Python
在django模板中实现超链接配置
2019/08/21 Python
python使用gdal对shp读取,新建和更新的实例
2020/03/10 Python
tensorflow常用函数API介绍
2020/04/19 Python
使用Keras画神经网络准确性图教程
2020/06/15 Python
Python collections.deque双边队列原理详解
2020/10/05 Python
学习计划书怎么写
2014/09/15 职场文书
运动会报道稿300字
2014/10/02 职场文书
先进单位申报材料
2014/12/25 职场文书
诚信考试承诺书范文
2015/04/29 职场文书
国庆节新闻稿
2015/07/17 职场文书
四年级数学教学反思
2016/02/16 职场文书
世界上超棒的8种逻辑思维
2019/08/06 职场文书
redis的list数据类型相关命令介绍及使用
2022/01/18 Redis