常用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 使用requests模块发送GET和POST请求的实现代码
Sep 21 Python
使用Python操作excel文件的实例代码
Oct 15 Python
python爬虫爬取淘宝商品信息
Feb 23 Python
Python列表生成式与生成器操作示例
Aug 01 Python
Python 比较文本相似性的方法(difflib,Levenshtein)
Oct 15 Python
python微元法计算函数曲线长度的方法
Nov 08 Python
Python中logging.NullHandler 的使用教程
Nov 29 Python
Python实现平行坐标图的两种方法小结
Jul 04 Python
python sqlite的Row对象操作示例
Sep 11 Python
python已协程方式处理任务实现过程
Dec 27 Python
python 模拟登陆github的示例
Dec 04 Python
python实战之一步一步教你绘制小猪佩奇
Apr 22 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
dede3.1分页文字采集过滤规则详说(图文教程)
2007/04/03 PHP
php 方便水印和缩略图的图形类
2009/05/21 PHP
PHP curl模拟浏览器采集阿里巴巴的实现代码
2011/04/20 PHP
PHP自定session保存路径及删除、注销与写入的方法
2014/11/18 PHP
php短网址和数字之间相互转换的方法
2015/03/13 PHP
Javascript技巧之不要用for in语句对数组进行遍历
2010/10/20 Javascript
javaScript复制功能调用实现方案
2012/12/13 Javascript
jquery选择checked在ie8普通模式下的问题
2014/02/12 Javascript
详解JavaScript 中的 replace 方法
2016/01/01 Javascript
window.onload绑定多个事件的两种解决方案
2016/05/15 Javascript
JS变量中有var定义和无var定义的区别以及es6中let命令和const命令
2017/02/19 Javascript
vue配置多页面的实现方法
2018/05/22 Javascript
[00:36]DOTA2勇士令状莱恩声望物品——冥晶之厄展示
2018/05/25 DOTA
Python中实现参数类型检查的简单方法
2015/04/21 Python
用Python进行TCP网络编程的教程
2015/04/29 Python
Python实现登录人人网并抓取新鲜事的方法
2015/05/11 Python
详解Python编程中time模块的使用
2015/11/20 Python
利用Python实现颜色色值转换的小工具
2016/10/27 Python
Pandas 对Dataframe结构排序的实现方法
2018/04/10 Python
python 脚本生成随机 字母 + 数字密码功能
2018/05/26 Python
anaconda3安装及jupyter环境配置全教程
2020/08/24 Python
浅谈Selenium+Webdriver 常用的元素定位方式
2021/01/13 Python
什么是用户模式(User Mode)与内核模式(Kernel Mode) ?
2015/09/07 面试题
应聘自荐书
2013/10/08 职场文书
大学生专科毕业生自我评价
2013/11/17 职场文书
门诊挂号室室长岗位职责
2013/11/27 职场文书
自主招生自荐信
2013/12/08 职场文书
道德之星事迹材料
2014/05/03 职场文书
一次性工伤赔偿协议书范本
2014/11/25 职场文书
医德医风自我评价2015
2015/03/03 职场文书
出国留学导师推荐信
2015/03/26 职场文书
2015年企业员工工作总结范文
2015/05/21 职场文书
开学第一周总结
2015/07/16 职场文书
个人的事迹材料怎么写
2019/04/24 职场文书
励志语录:时光飞逝,请学会珍惜所有的人和事
2020/01/16 职场文书
戴尔Win11系统no bootable devices found解决教程
2022/09/23 数码科技