python2学习笔记

本文对python2的学习过程的遇到的一些问题作一下简单记录,条目会很多,每条记录的内容可能会很少,做个记号。这是一个长期记录过程,以后会继续补充。

类型转换

1
2
3
4
5
int('12') #字符串转整型
float('12.2') #字符串转浮点型
str(12) #数值型转字符串
chr(97) #ascii码转字符
ord('a') #字符转ascii码

list不常用操作

1
2
3
4
5
list(set(a)) #去重
list(set(a).intersection(set(b))) #获得两个list的交集
list(set(a).union(set(b))) #获得两个list的并集
#获得两个list的差集
list(set(a).difference(set(b))) #a中有而b中没有的

exec与eval

1
2
3
exec('print 1+2') #exec用于执行语句,无返回值
print eval('1+2') #eval用于返回表达的值
execfile('a.py') #执行文件

生成器

1
2
3
4
5
6
def func():
for i in range(10):
yield(i)
a = func()
b = (i for i in range(10))
c = iter(range(10))

中文编码

1
2
3
4
5
6
7
8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding()
import codecs
f = codecs.open('a.txt', 'w', 'utf-8')
f.write(u'中文')
f.close()
1
2
3
4
5
s1 = '中文'
s2 = u'中文'
print s1 == s2
print s1.decode('utf-8') == s2
print s1 == s2.encode('utf-8')
1
2
3
4
5
6
7
8
#coding=utf-8
import sys
s = '汉字'
print s
print s.decode('utf-8')
print s.decode('utf-8').encode('gbk')
type1 = sys.getfilesystemencoding()
print s.decode('utf-8').encode(type1)

爬虫

1
2
3
4
5
import urllib
url = 'http://www.163.com'
page = urllib.urlopen(url)
html = page.read()
print html

正则表达式

1
2
3
import re
s = 'hello\nworld'
re.search(r'hello.*world', s, re.S) #加re.S使匹配所有字符,包括\n

键盘中断

1
2
3
4
5
try:
while Ture:
pass
except KeyboardInterrupt:
sys.exit(0)

文件操作

文件操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
os.mknode('a.txt') #创建空文件
f = open('a.txt', 'w') #以写方式打开文件
#w|a|r+|w+|a+|rb|wb|ab|rb+|wb+|ab+
f.read([size]) #读取文件
f.readline([size]) #按行读取文件
f.readlines([size]) #按行将文件内容读取到list
f.write(str) #将str写入文件
f.writelines(list) #将list写入文件
f.close() #关闭文件
f.flush() #将缓冲区的内容写入硬盘
f.fileno() #返回一个长整型的文件描述符
f.isatty() #判断文件是否为终端设备
f.tell() #返回文件标记的当前位置
f.next() #返回文件下一行
f.seek(offset, whence) #文件标记移动,whence=0头|1当前|2尾
f.truncate([size]) #裁剪文件

目录操作

1
2
3
4
5
6
7
8
9
os.mkdir('test') #创建目录
shutil.copyfile('old', 'new') #拷贝文件
shutil.copy('olddir', 'new') #拷贝目录
shutil.copytree('olddir', 'newdir') #拷贝目录,newdir必须不存在
os.rename('old', 'new') #重命名文件或目录
shutil.move('old', 'new') #移动文件或目录
os.remove() #删除文件
shutil.rmtree('dir') #空目录、有内容的目录都能删
os.chdir('path') #切换工作路径

常用文件/目录操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#python中对文件/文件夹操作主要涉及到os和shutil模块。
os.getcwd() #获得当前工作目录
os.listdir('.') #获得当前目录下的所有文件/文件夹名
os.remove('a.txt') #删除文件
os.removedirs("") #删除多个目录
os.path.isfile('a.txt') #检查是否为文件
os.path.isdir('a') #检查是否为目录
os.path.isabs() #检查是否为绝对路径
os.path.exists() #是否存在
os.path.split() #分割目录和文件
os.path.splitext() #分割文件名和扩展名
os.path.dirname() #获得文件目录名
os.path.basename() #获得文件名
os.system('ls') #运行系统命令
os.getenv() #获得环境变量
os.putenv() #设置环境变量
os.linesep #获得当前平台使用的终止符
os.name #获得当前平台名
os.rename(old, new) #重命名
os.makedirs(r'/root/a/b/c') #创建多级目录
os.mkdir('test') #创建目录
os.stat(file) #获得文件属性
os.chmod(file) #修改文件属性和时间戳
os.exit() #终止当前进程
os.path.getsize(filename) #获得文件大小

标准库

库在python中称为模块,就是个.py文件。

内建函数和异常模块

  • builtin模块是定义内建函数的模块,len/int/range……等函数都来自该模块。
  • exceptions模块是定义内建异常的模块。

python在启动时自动导入这两个模块。

操作系统接口模块

python使用了许多POSIX标准API和标准C语言库的模块,它们为底层操作系统提供了平台独立的接口。这类模块包括如下:

  • os:提供文件和进程处理功能。
  • os.path:提供平台独立的文件名处理功能。
  • time/datetime:提供时间/日期处理功能。

类型支持模块:string、math、cmath等。

正则表达式模块

re模块为python提供了正则表达式支持功能,正则表达式用于匹配字符串和特定字符。

语言支持模块

  • sys:访问解释器相关参数。
  • operator:提供和内建操作符相同的函数。
  • copy:提供对象复制功能。
  • gc:提供了对垃圾收集的相关控制功能。

外部命令调用

1
2
3
4
5
6
7
8
"""使用os模块"""
os.system('ifconfig') #执行外部命令,无法获得输出值
p = os.popen('ifconfig') #可以获得输出值
s = p.read()
"""使用subprocess模块"""
sub = subprocess.Popen('ifconfig', shell=True, stdout=subprocess.PIPE)
sub.wait()
print sub.read()

文件内容转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""二进制文件与base64编码文件互转"""
import base64
fr = open(r'e:\1.jpg', 'rb')
fw = open(r'e:\1.jpg.base64', 'w')
base64.encode(fr, fw)
fr.close()
fw.close()
fr = open(r'e:\1.jpg.base64', 'r')
fw = open(r'e:\11.jpg', 'wb')
base64.decode(fr, fw)
fr.close()
fw.close()
"""二进制文件与十六进制文件互转"""
import binhex
r = r'e:\1.jpg'
w = r'e:\1.jpg.hex'
binhex.binhex(r, w)
w1 = r'e:\111.jpg'
binhex.hexbin(w, w1)

操作mysql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#coding=utf-8
import MySQLdb
conn=MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='123456',
db='test',
)
cur=conn.cursor()
#创建数据表
#cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
#插入一条数据
#cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
#修改查询条件的数据
#cur.execute("update student set class='3 year 1 class' where name = 'Tom'")
#删除查询条件的数据
#cur.execute("delete from student where age='9'")
cur.close()
conn.commit()
conn.close()

简单的web服务器

python -m SimpleHTTPServer 8000 #python2

python -m http.server 8000 #python3

输出不换行

1
2
3
4
5
6
import sys
sys.stdout.write('hello,')
sys.stdout.write('world.')
sys.stdout.flush()
print 'hello,',
print 'world.'

时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#coding=utf-8
import time
#时间串转成时间数组
timestr = '2011-11-11 11:11:11'
print timestr
timearray = time.strptime(timestr, '%Y-%m-%d %H:%M:%S')
print timearray
#时间数组转成时间戳
timestamp = int(time.mktime(timearray))
print timestamp
#时间数组转成时间串
timestr = time.strftime('%Y/%m/%d %H:%M:%S', timearray)
print timestr
#获得当前系统时间时间戳
timestamp = int(time.time())
#时间戳转成时间数组
timearray = time.localtime(timestamp)
#时间数组转成时间串
timestr = time.strftime('%Y-%m-%d %H:%M:%S', timearray)
print timestr
#今天、昨天和明天
import datetime
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)

动态加载模块

1
2
3
4
#import imp
#module = imp.load_module('a', *imp.find_module('a'))
module = __import__('a')
print module.add_func(2,3)

dict转json

1
2
3
4
5
6
7
import json
d = dict(name='aaa', age = 20, socre = 88)
print d
j = json.dumps(d)
print j
d1 = json.loads(j)
print d1

编码解码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#coding=utf-8
import sys
print sys.getdefaultencoding()
s = u"中国"
print s
print s.encode('gb2312')
print s.encode('utf8')
###########################
s1 = "山东"
if isinstance(s1, unicode):
#s1=u"山东"
print s1.encode('gb2312')
else:
#s1="山东"
print s1.decode('utf-8').encode('gb2312')

异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
s = raw_input("input your age:")
if s == "":
raise Exception("input must no be empty")
try:
i = int(s)
except ValueError:
print "could not convert data to an integer"
except:
print "unknown exception"
else:
print "you are %d" %i, " years old"
finally:
print "goodbye"

格式化打印

1
2
3
4
5
6
# -*- coding: cp936 -*-
print "你好,世界"
print """
中华人民共和国万岁
世界人民大团结万岁
"""

定时器

1
2
3
4
5
6
7
8
9
#encoding: UTF-8
import threading
def sayhello():
print "hello,world."
global t
t = threading.Timer(5.0, sayhello)
t.start()
t = threading.Timer(5.0, sayhello)
t.start()