Python的持久储存

print()的file参数控制将数据发送或保存在哪里。

在包中创建一个sketch.txt文件,实现将文件中的内容分别放入俩个man_data.txt和other_data.txt文件中

# 将sketch.txt文件中的内容按不同的角色以俩个列表的形式输出

try:
    # open既可以实现读文件,也可以实现写文件
    the_file = open("sketch.txt")
    # 写文件时要指定访问模式,文件不存在就先创建文件
    out_man = open("man_data.txt", "w")
    out_other = open("other_data.txt", "w")
    for each_line in the_file:
        try:
            (role, line_spoken) = each_line.split(":", 1)
            # 从字符串中去掉空白符
            line_spoken = line_spoken.strip()
            # 根据文本文件中的讲话人更新列表
            if role == 'Man':
                # 将line_spoken里面的内容写到file所指向的文件中去
                print(line_spoken, file=out_man)
            elif role == 'Other Man':
                print(line_spoken, file=out_other)
        except ValueError:
            pass
    # 关闭掉文件
    the_file.close()
    out_other.close()
    out_man.close()
except IOError:
    print("文件错误", end="")

创建一个nester模块,实现一个屏幕输出和文件输出俩种方式

import sys


# 创建一个nester模块,实现在屏幕或者文件中显示内容,缺省参数为在屏幕输出
def print_lol(the_list, indent=False, level=0, fh=sys.stdout):
    for each_line in the_list:
        if isinstance(each_line, list):
            print_lol(each_line, indent, level=level + 1, fh=sys.stdout)
        else:
            if indent:
                for top_stop in range(level):
                    print("\t", end="", file=fh)
            print(each_line, file=fh)

实现nester模块中的方法以及用pickle方法高效的保存或恢复磁盘中的数据对象

import chapter4.nester
man = []
other = []
try:
    the_file = open("sketch.txt")
    for each_line in the_file:
        try:
            (role, line_spoken) = each_line.split(":", 1)
            if role == "Man":
                man.append(line_spoken)
            elif role == "Other Man":
                other.append(line_spoken)
        except ValueError:
            pass
# 为异常对象给定一个异常名,将其作为错误消息的一部分,由于异常对象与字符串不兼容,所以将异常对象转化为字符串
except IOError as err:
    print("文件不存在:" + str(err))
# finally中关闭文件,当文件发生异常时也可以关闭文件,防止写入的数据被破坏
finally:
    # 对finally增加一个测试,判断文件名是否在当前作用域中,locals方法返回当前作用域中定义的所有名的集合
    if 'sketch' in locals():
        the_file.close()
"""
# 将内容输出到文件中
try:
    # 用with代替finally语句,不需要考虑关闭语句,with语句利用了上下文管理协议技术
    with open("manSpeak.txt", "w") as man_out:
        # 调用nester模块的方法,实现在文件或屏幕显示
        chapter4.nester.print_lol(man, True)
        chapter4.nester.print_lol(man, fh=man_out)
    with open("otherSpeak.txt", "w") as other_out:
        chapter4.nester.print_lol(other, True, fh=other_out)
except IOError as err:
    print("文件错误:" + str(err))

"""
# 使用pickle功能实现数据的保存(dump)与恢复(load)
import pickle
try:
    with open("manSpeak.txt", "wb")as out_man, open("otherSpeak.txt","wb") as out_other:
        pickle.dump(man, out_man)
        pickle.dump(other, out_other)
# 抛出异常为PickleError
except pickle.PickleError as p:
    print("pickling error:" + str(p))

pickle,print_lol,print的结合使用

import pickle
import chapter4.nester
man_data = []
other_data = []
# 用Pickle取出数据
try:
    with open("manSpeak.txt","rb") as read_man, open("otherSpeak.txt", "rb") as read_other:
        man_data = pickle.load(read_man)
        other_data = pickle.load(read_other)
except IOError as io:
    print("文件不存在" + str(io))
except pickle.PickleError as p:
    print("pickling Error" + str(p))
# 用nester模块中的方法将数据读取并展示出来
chapter4.nester.print_lol(man_data, True)
# 标准输出语句可以随机访问列表的每一项
# 输出list的第一项
print(man_data[0])
# 输出list的最后一项
print(other_data[-1])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值