小白教程

 找回密码
 立即注册

pickle 模块

发布者: 小白教程

Python提供了一个称为的标准模块pickle,您可以使用该模块任何普通的Python对象存储在文件中,然后再将其取回。这称为持久存储对象

示例(另存为io_pickle.py):

import pickle

# The name of the file where we will store the object
shoplistfile = 'shoplist.data'
# The list of things to buy
shoplist = ['apple', 'mango', 'carrot']

# Write to the file
f = open(shoplistfile, 'wb')
# Dump the object to a file
pickle.dump(shoplist, f)
f.close()

# Destroy the shoplist variable
del shoplist

# Read back from the storage
f = open(shoplistfile, 'rb')
# Load the object from the file
storedlist = pickle.load(f)
print(storedlist)
f.close()

输出:

$ python io_pickle.py
['apple', 'mango', 'carrot']

这个怎么运作

要存储一个对象在一个文件中,我们必须首先open在文件中W¯¯仪式b inary模式,然后调用dump的功能pickle模块。此过程称为酸洗

接下来,我们使用返回对象loadpickle模块功能来检索对象。此过程称为解

统一码

到目前为止,当我们一直在编写和使用字符串,或读写文件时,我们仅使用简单的英文字符。英文和非英文字符都可以用Unicode表示(请参阅本节末尾的文章以了解更多信息),并且Python 3默认情况下存储字符串变量(请考虑一下我们使用单,双或三重编写的所有文本)引号)。

注意:如果您使用的是Python 2,并且我们希望能够读写其他非英语语言,则需要使用该unicode类型,并且所有类型均以字符开头u,例如u"hello world"

>>> "hello world"
'hello world'
>>> type("hello world")
<class 'str'>
>>> u"hello world"
'hello world'
>>> type(u"hello world")
<class 'str'>

通过Internet发送数据时,我们需要以字节为单位发送数据……您的计算机容易理解。将Unicode(Python在存储字符串时使用的)转换为字节的规则称为编码。使用的一种流行编码是UTF-8。我们可以通过在open函数中使用简单的关键字参数来以UTF-8进行读写

# encoding=utf-8
import io

f = io.open("abc.txt", "wt", encoding="utf-8")
f.write(u"Imagine non-English language here")
f.close()

text = io.open("abc.txt", encoding="utf-8").read()
print(text)

这个怎么运作

我们在第一个open语句中使用io.open,然后encoding在解码消息时在第二个open语句中使用参数,然后在第二个open语句中使用参数。请注意,在文本模式下,仅应在open语句中使用编码。

每当我们u像上面使用的那样编写使用Unicode文字的程序(通过在字符串之前放置一个)时,我们都必须确保Python本身被告知我们的程序使用UTF-8,并且必须# encoding=utf-8 在顶部放置 注释。我们的程序。

上一篇:Python中的输入下一篇:异常情况

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 01:39 , Processed in 0.018833 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部