其实持久存储不仅仅包含文件,还包括数据库等,本章先介绍一部分,先熟悉一下。
熟悉python数据
#!/usr/bin/python
# -*- coding: utf-8 -*-
man = []
other = []
try:
data = open('sketch.txt')
for each_line in data:
try:
(role,line_spoken) = each_line.split(':',1)
line_spoken = line_spoken.strip() #这里的解读是:这里不是直接处理line_spoken字符串,python 不会改变字符串,他会创建一个新的字符串出来然后执行类似如strip()的方法,然后将返回值赋值到原来的字符串
if role == 'Man':
man.append(line_spoken)
elif role == 'Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print('The datafile is missing!')
print (man)
print (other)
print ("Norwegian Blues XXXX",file=out) 是python 3.0用法,如果旧版本的python就是用
data.write(result)
需要注意的是,如果要写入文件,那么打开文件的时候要用w写入模式才行,读取的话是r。
对于try:except无法处理的情况时候,使用finally
finally是代表总会执行而不论try:except的报错
#!/usr/bin/python
# -*- coding: utf-8 -*-
man = []
other = []
try:
data = open('sketch.txt')
for each_line in data:
try:
(role,line_spoken) = each_line.split(':',1)
line_spoken = line_spoken.strip() #这里的解读是:这里不是直接处理line_spoken字符串,python 不会改变字符串,他会创建一个新的字符串出来然后执行类似如strip()的方法,然后将返回值赋值到原来的字符串
if role == 'Man':
man.append(line_spoken)
elif role == 'Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print('The datafile is missing!')
finally:
data.close()
详细打印捕获到的错误信息
#!/usr/bin/python
# -*- coding: utf-8 -*-
man = []
other = []
try:
data = open('sketch.txt')
for each_line in data:
try:
(role,line_spoken) = each_line.split(':',1)
line_spoken = line_spoken.strip() #这里的解读是:这里不是直接处理line_spoken字符串,python 不会改变字符串,他会创建一个新的字符串出来然后执行类似如strip()的方法,然后将返回值赋值到原来的字符串
if role == 'Man':
man.append(line_spoken)
elif role == 'Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError as err:
print('The datafile is missing!' + str(err)) # 捕获详细的错误信息,这个信息需要str格式化
finally:
data.close()
例如详细的错误信息会显示: File error: XXXX NO such file or directory:'sketch.txt'
用with代替open
因为with 会自动关闭文件,而不用像open那样要在结尾是用close关闭
with open('its.txt',"w") as data:
print data
学习是用pickle
pickle的使用原因是它是python的专用持久存储方式,可以不用理会格式问题,直接保存,直接使用,这就是他的闪光之处。
用dump保存,用load恢复
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pickle
with open('mydata.pickle','w') as mysavedata:
pickle.dump([1,2,3],mysavedata)
a = []
with open('mydata.pickle','r') as myrestoredata:
a = pickle.load(myrestoredata)
print a
原文链接:http://www.godblessyuan.com/2015/04/27/head_first_python_chapter_5_lea...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。