Head First Python(持久存储)

 

程序生成数据

import os
os.chdir('D:\\Python33\HeadFirstPython\chapter3')
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()    #“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 data file is missing')

以写模式打开文件
>>>out=open("data.out","w")              #使用写模式打开文件data.out

>>>print("Norwegian Blues stun easily.",file=out)             #将内容写到数据文件对象out中

>>>out.close()


try:
        man_file= open('man_data.txt', 'w') 
                print(man, file=man_file)
        other_file=open('other_data.txt', 'w') 
                print(other, file=other_file)
        man_file.close()

        other_file.close()
except IOError :
        print('File error' )

发生异常后文件会保持打开无法关闭,用finally扩展try

try:
        man_file= open('man_data.txt', 'w') 
                print(man, file=man_file)
        other_file=open('other_data.txt', 'w') 
                print(other, file=other_file)

except IOError :
        print('File error' )

finally:          #finally组总会执行,不管try/except中发生什么异常

        man_file.close()

        other_file.close()

知道错误类型还不够

打开一个根本不存在的文件

try:
        data= open('missing.txt') 
         print(data.readline(),end='')

except IOError :
        print('File error' )

finally:       

data.close()

错误信息如下

File error
Traceback (most recent call last):
  File "<pyshell#2>", line 7, in <module>
    data.close()
NameError: name 'data' is not defined

文件不存在,数据文件对象并未创建,这样就不能在数据对象上调用close()方法,所有有一个NameErroe错误。

locals()BIF会返回当前作用域中定义的所有名的一个集合。

finally:

if 'data' in locals():

data.colse()

做一个小的改动使得可以在代码中使用这个异常

except IOError as err:                    #为异常对象给定一个名

print('File error: '+str(err))      #使用str()BIF要求异常对象表现为一个字符串


File error: [Errno 2] No such file or directory: 'missing.txt'  #得到一个特定的错误信息,指出到底是哪里出了问题

用with处理文件

try:  #with语句自动处理所有已打开文件的关闭工作,即使出现异常也不例外。with语句也使用as关键字。
        with open('man_data.txt', 'w') as man_file:
                print(man, file=man_file)
        with open('other_data.txt', 'w') as other_file:
                print(other, file=other_file)
except IOError as err:
        print('File error:' + str(err))

检查文件夹,两个数据文件已经出现。

默认格式对文件并不合适

默认的,printed()会模仿Python解释器世纪存储列表数据的格式来显示你的数据。

何不修改print_lol()?

标准输出(Standard Optput)是使用“print()”BIF时代码写数据的默认位置,通常是屏幕。在Python中,标准输出是指"sys.stdout",

可以从标准库"sys"模块导入。

import sys
def print_lol(the_list, indent=False, level=0, fh=sys.stdout):
    for each_item in the_list:
        if isinstance(each_item, list):
            print_lol(each_item, indent, level+1, fh)
        else:
            if indent:
                for tab_stop in range(level):
                    print("\t",end='', file=fh)
            print(each_item, file=fh)

向函数增加第4个参数,用来标识将把数据写入哪个位置。with语句中的代码不再使用"print()"BIF,导入"nester"模块,调用"print_lol()",数据会分行显示。

“腌制”数据

标准版pickle,它可以保存和加载几乎任何Python数据对象,包括列表。

用dump保存,用load恢复

import pickle             #导入pickle模块
 ...
with open('mydata.pickle','wb') as mysavedata:         #保存数据,'b'告诉Python以二进制模式打开数据文件
pickle.dump([1,2,'three'],mysavedata)
...
with open('mydata.pickle','rb') as myrestoredata:       #恢复数据,赋值至一个标识符
a_list=pickle.load(myrestoredata)
print(a_list)             


腌制或者解除数据腌制时如果出了问题,pickle模块会产生一个PickleError类型的异常。

try:
        with open('man_data.txt', 'wb') as man_file:
                pickle.dump(man, man_file)
        with open('other_data.txt', 'wb') as other_file:
                pickle.dump(other, other_file)
except IOError as err:
        print('File error:' + str(err))
except pickle.PickleError as perr:
        print('Pickling error:' + str(perr))

将原先腌制的数据加载到另一个程序pickle时表现很出色

import pickle
import nester
import os
os.chdir('D:\\Python33\HeadFirstPython\chapter3')
new_man=[]
try:
    with open('man_data.txt', 'rb') as man_file:
        new_man=pickle.load(man_file)
except IOError as err:
    print('File error:' + str(err))
except pickle.PickleError as perr:
    print('Pickling error:' + str(perr))
nester.print_lol(new_man)

                                    





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值