常用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实现学校管理系统
Jan 11 Python
python中yaml配置文件模块的使用详解
Apr 27 Python
Python中实现单例模式的n种方式和原理
Nov 14 Python
使用Filter过滤python中的日志输出的实现方法
Jul 17 Python
python opencv实现证件照换底功能
Aug 19 Python
PyQt5 closeEvent关闭事件退出提示框原理解析
Jan 08 Python
动态设置django的model field的默认值操作步骤
Mar 30 Python
浅谈Python 中的复数问题
May 19 Python
Python深度学习之实现卷积神经网络
Jun 05 Python
Python编解码问题及文本文件处理方法详解
Jun 20 Python
python使用matplotlib绘制图片时x轴的刻度处理
Aug 30 Python
Python实现视频中添加音频工具详解
Dec 06 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
关于拼配咖啡,你要知道
2021/03/03 咖啡文化
php.ini中的php-5.2.0配置指令详解
2008/03/27 PHP
php验证手机号码(支持归属地查询及编码为UTF8)
2013/02/01 PHP
PHP魔术方法以及关于独立实例与相连实例的全面讲解
2016/10/18 PHP
PHP内置函数生成随机数实例
2019/01/18 PHP
PHP批斗大会之缺失的异常详解
2019/07/09 PHP
javascript 日期时间函数(经典+完善+实用)
2009/05/27 Javascript
jQuery 核心函数以及jQuery对象
2010/03/23 Javascript
javascript中的prototype属性实例分析说明
2010/08/09 Javascript
两个数组去重的JS代码
2013/12/04 Javascript
使用变量动态设置js的属性名
2014/10/19 Javascript
小心!AngularJS结合RequireJS做文件合并压缩的那些坑
2016/01/09 Javascript
jquery模拟实现鼠标指针停止运动事件
2016/01/12 Javascript
JavaScript数组的一些奇葩行为
2016/01/25 Javascript
基于vue的换肤功能的示例代码
2017/10/10 Javascript
详解Vue单元测试case写法
2018/05/24 Javascript
微信小程序学习笔记之表单提交与PHP后台数据交互处理图文详解
2019/03/28 Javascript
JS实现简易图片自动轮播
2020/10/16 Javascript
基于elementUI竖向表格、和并列的案例
2020/10/26 Javascript
基于vue与element实现创建试卷相关功能(实例代码)
2020/12/07 Vue.js
[40:57]TI4 循环赛第二日 iG vs EG
2014/07/11 DOTA
[58:57]2018DOTA2亚洲邀请赛3月29日小组赛B组 Effect VS VGJ.T
2018/03/30 DOTA
Python的Urllib库的基本使用教程
2015/04/30 Python
详解Python中的各种函数的使用
2015/05/24 Python
python安装模块如何通过setup.py安装(超简单)
2018/05/05 Python
python中树与树的表示知识点总结
2019/09/14 Python
Python Numpy 自然数填充数组的实现
2019/11/28 Python
Python 使用office365邮箱的示例
2020/10/29 Python
银行出纳岗位职责
2013/11/25 职场文书
大二学习计划书范文
2014/04/27 职场文书
图书馆标语
2014/06/19 职场文书
学校学习雷锋活动总结
2014/07/03 职场文书
学校联谊协议书
2014/09/16 职场文书
财政局党的群众路线教育实践活动整改方案
2014/09/21 职场文书
员工福利申请报告
2015/05/15 职场文书
python通过新建环境安装tfx的问题
2022/05/20 Python