《Head First Python》笔记 第四章 持久存储

感受比Java简单许多啊...函数

持久存储 Persistent:Saving data to file

将基于内存的数据存储到磁盘上测试

对于文件的处理,通常是打开文件,获取文件内容,进行处理。处理结果能够在屏幕上显示,也能够保存在其余文件中。好比上一章对话的例子,将不一样人说的话显示,或者保存在文件中。ui

在此输入图片描述

Python中的字符串是不可变的(数值类型也不可变),strip()方法会建立一个新的字符串,将结果返回给line_spokenthis

Python变量只包含数据对象的一个引用,数据对象才真正包含数据(联想:变量无类型)rest

Open your file in write mode(写模式)

使用open() BIF打开磁盘文件时,能够指定使用什么访问模式,默认r模式(读)。code

写模式即w模式。orm

在此输入图片描述

默认地,print() BIF显示数据时会使用标准输出(一般是屏幕)。要把数据写至一个文件,须要使用file参数来指定所使用的数据文件对象(默认file=sys.stdout):对象

在此输入图片描述

写入完成后,必定要关闭文件,确保全部数据都写至磁盘。这称为刷新输出(flushing),这一点很是重要。图片

out.close() # 后面会讲到使用with关键字帮助处理这个过程

在此输入图片描述

在文件处理过程当中,若是出现错误,则打开的文件将不会关闭,可使用finally进行关闭。ip

在此输入图片描述

When an error occurs at runtime, Python raises an exception of the specific type (such as IOError, ValueError , and so on). Additionally, Python creates an exception object that is passed as an argument to your except suite.

with处理文件

下图两种方法实现同样的功能

在此输入图片描述

知识点

  1. 当文件不存在时,数据文件对象并未建立,即data不存在,调用close()方法会有异常,locals() BIF会返回当前做用域中的变量集合,使用if 'data' in locals() :进行测试。
  2. Python解释器将一个异常对象传入except组,as关键字能够将异常对象赋值至一个标识符,但不能直接打印,应该使用str() BIF把异常对象转换为字符串。
  3. The str() BIF can be used to access the stringed representation of any data object that supports the conversion.

因为处理文件时try/except/finally模式至关经常使用,因此Python提供了一个语句来抽象出相关的一些细节。The with statement, when used with files, can dramatically reduce the amount of code you have to write, because it negates the need to include a finally suite to handle the closing of a potentially opened data file.

with语句会自动处理全部已打开文件的关闭工做,即便出现异常也不例外。with语句也使用as关键字。

在此输入图片描述

The with statement takes advantage of a Python technology called the context management protocol(上下文管理协议).

print() BIF:

在此输入图片描述

Pickle your data

Python ships with a standard library called pickle, which can save and load almost any Python data object, including lists.至关因而Java对象的序列化。以下图:

在此输入图片描述

You can, for example, store your pickled data on disk, put it in a database, or transfer it over a network to another computer.

When you are ready, reversing this process unpickles your persistent pickled data and recreates your data in its original form within Python's memory:

在此输入图片描述

标准库存的pickle模块容许你容易而高效地将Python数据对象保存到磁盘以及从磁盘恢复。

dump保存,用load恢复

Using pickle is straightforward: import the required module, then use dump() to save your data and, some time later, load() to restore it. The only requirement when working with pickled files is that they have to be opened in binary access mode:

在此输入图片描述

dump()load()方法都会抛出pickle.PickleError,所以须要进行捕获。

在此输入图片描述

这样保存list的方式,能够不使用print(list, fiie='man.txt')的方式,而使用pickle.dump(list, 'man.txt')的方式。

本章还改进了nester.py,为print_lol()函数加入了fh=sys.stdout可选参数。可与load()结合使用打印列表。

相关文章
相关标签/搜索