简介
Python 程序员大量使用数组、列表和字典作为序列化的数据结构。持久地存储这些数据结构需要一个文件或一个数据库才能正常工作。
在这篇文章中,我们将看看如何将一个列表写入文件,以及如何将这个列表读回内存。
为了在文件中写入数据,以及从文件中读取数据,Python 编程语言提供了处理单行的标准方法write() 和read() ,以及处理多行的writelines() 和readlines() 。此外,pickle 和json 模块也允许以巧妙的方式处理序列化的数据集。
使用read()和write()方法
要处理字符(字符串),基本的read() 和write() 方法效果很好。将这样的列表逐行保存到文件listfile.txt ,可以按以下方式进行:
# Define a list of places
places = ['Berlin', 'Cape Town', 'Sydney', 'Moscow']
with open('listfile.txt', 'w') as filehandle:
for listitem in places:
filehandle.write(f'{listitem}\n')
listitem ,首先通过换行扩展"\n" ,然后存储到输出文件中。现在我们可以看看如何将整个列表从文件listfile.txt 中读回内存:
# Define an empty list
places = []
# Open the file and read the content in a list
with open('listfile.txt', 'r') as filehandle:
for line in filehandle:
# Remove linebreak which is the last character of the string
curr_place = line[:-1]
# Add item to the list
places.append(curr_place)
请记住,你需要删除字符串结尾的换行符。在这种情况下,Python 也允许对字符串进行列表操作,这对我们有帮助。这个移除操作只是作为对字符串本身的一个列表操作,它保留了除最后一个元素之外的所有内容。这个元素包含字符"\n" ,在 UNIX/Linux 系统中代表换行。
使用writelines()和readlines()方法
正如本文开头提到的,Python 还包含两个方法 -writelines() 和readlines() - 分别用于在一个步骤中写入和读取多个行。让我们把整个列表写到磁盘上的一个文件:
# Define a list of places
places_list = ['Berlin', 'Cape Town', 'Sydney', 'Moscow']
with open('listfile.txt', 'w') as filehandle:
filehandle.writelines(f"{place for place in places_list}\n")
为了从磁盘上的文件中读取整个列表,我们需要:
# Define an empty list
places = []
# Open the file and read the content in a list
with open('listfile.txt', 'r') as filehandle:
filecontents = filehandle.readlines()
for line in filecontents:
# Remove linebreak which is the last character of the string
curr_place = line[:-1]
# Add item to the list
places.append(curr_place)
上面的代码采用了从其他编程语言中借用的比较传统的方法。让我们用更多的Pythonic方式来写它:
# Define an empty list
places = []
# Open the file and read the content in a list
with open('listfile.txt', 'r') as filehandle:
places = [current_place.rstrip() for current_place in filehandle.readlines()]
首先,通过readlines() 读取文件内容。第二,在一个for 循环中,从每一行开始,使用rstrip() 方法删除换行符。第三,该字符串作为一个新的列表项被添加到地方列表中。
与之前的列表相比,代码要紧凑得多,但对于Python初学者来说可能更难阅读。
使用Joblib模块
到目前为止,最初解释的方法是以人类可以阅读的方式来存储列表的--相当程度上是文件中的一个顺序列表。这对于创建简单的报告或输出供用户进一步使用的输出文件,如CSV文件,是非常好的。然而,如果你的目的只是将一个列表序列化成一个文件,以后可以加载,就没有必要以人类可读的格式存储它。
joblib 模块提供了最简单的方法来转储一个 Python 对象 (真的可以是任何对象):
import joblib
places = ['Berlin', 'Cape Town', 'Sydney', 'Moscow']
# Dumps into file
joblib.dump(places, 'places.sav')
# Loads from file
places = joblib.load('places.sav')
print(places) # ['Berlin', 'Cape Town', 'Sydney', 'Moscow']
joblib 仍然是最简单、最干净的方式,以一种有效的格式序列化对象,并在以后加载它们。你可以使用任何任意的格式,比如 , , 等等。这其实并不重要-- 和像 这样的替代品都可以很好地读取文件。.sav .data joblib pickle
使用pickle模块
作为joblib 的替代品,我们可以使用pickle!它的dump() 方法将列表有效地存储为一个二进制数据流。首先,输出文件listfile.data 被打开进行二进制写入("wb" )。其次,使用dump() 方法将列表存储在打开的文件中:
import pickle
places = ['Berlin', 'Cape Town', 'Sydney', 'Moscow']
with open('listfile.data', 'wb') as filehandle:
# Store the data as a binary data stream
pickle.dump(places, filehandle)
作为下一步,我们从文件中读取列表,方法如下。首先,输出文件listfile.data 被打开进行二进制读取 ("rb")。其次,使用load() 方法从文件中加载位置列表。
import pickle
with open('listfile.data', 'rb') as filehandle:
# Read the data as a binary data stream
placesList = pickle.load(filehandle)
这里的两个例子展示了字符串的使用。尽管,pickle 可以与所有种类的Python对象一起工作,如字符串、数字、自定义结构,以及Python提供的其他每一个内置数据结构。
建议:关于一般对象的腌制的详细指南,请阅读我们的 "如何在Python中纠错和解错对象"!
使用JSON格式
pickle 使用的二进制数据格式是专门针对Python的。为了提高不同程序之间的互操作性,JavaScript对象符号(JSON)提供了一种易于使用和人类可读的模式,因此在序列化文件和通过API共享文件方面变得非常流行。
下面的例子演示了如何使用json模块将一个混合变量类型的列表写入输出文件。在打开输出文件进行写入后,dump() 方法使用JSON符号将基本列表存储在文件中。
import json
# Define list with values
basic_list = [1, "Cape Town", 4.6]
# Open output file for writing
with open('listfile.txt', 'w') as filehandle:
json.dump(basic_list, filehandle)
将输出文件的内容读回内存中,就像写数据一样简单。与dump() 相对应的方法被命名为load() 。
import json
# Open output file for reading
with open('listfile.txt', 'r') as filehandle:
basic_list = json.load(filehandle)
结论
我们上面展示的不同方法,从简单的写/读数据,到使用pickle和JSON通过二进制流转储/加载数据。这简化了持久地存储一个列表并将其读回内存的过程。