在Python中将数据结构保存到文件的最简单方法?

41 投票
7 回答
44577 浏览
提问于 2025-04-15 12:30

假设我有这样的东西:

d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }

有没有什么简单的方法可以通过编程把它保存到一个文件里,以便我以后可以在Python中加载?

我能不能在Python脚本里把它保存为Python源代码(而不是手动保存),然后以后用import导入它?

还是说我应该用JSON或者其他格式?

7 个回答

8

可以试试shelve模块,它能让你拥有一个可以长期保存的字典。比如说:

import shelve
d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }

shelf = shelve.open('shelf_file')
for key in d:
    shelf[key] = d[key]

shelf.close()

....

# reopen the shelf
shelf = shelve.open('shelf_file')
print(shelf) # => {'qwerty': [4, 5, 6], 'abc': [1, 2, 3]}
15

你可以选择以下链接了解更多信息:Python标准库 - 数据持久化。最合适的选择会根据你的具体需求而有所不同。

pickle 可能是最简单、功能最强大的工具,能够“把任意对象写入文件并恢复它”——它可以自动处理自定义类和循环引用。

如果你想要最佳的序列化性能(速度和空间),可以使用 cPickle 并设置为 HIGHEST_PROTOCOL

71

使用 pickle 模块。

import pickle
d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }
afile = open(r'C:\d.pkl', 'wb')
pickle.dump(d, afile)
afile.close()

#reload object from file
file2 = open(r'C:\d.pkl', 'rb')
new_d = pickle.load(file2)
file2.close()

#print dictionary object loaded from file
print new_d

撰写回答