如何在Python中将数据结构持续保存到文件中?

2024-04-27 04:13:41 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这样的东西:

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

有什么最简单的方法可以将它编程成一个文件,以后可以从python加载?

我能把它保存为python源代码吗(在python脚本中,而不是手动!),然后import它?

还是应该使用JSON或其他什么?


Tags: 文件方法import脚本json源代码编程手动
3条回答

尝试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]}

你挑吧:Python Standard Library - Data Persistance。哪一个是最合适的可以根据你的具体需要而有所不同。

^{}可能是最简单和最有能力的,只要“将任意对象写入文件并恢复它”,它就可以自动处理自定义类和循环引用。

为了获得最佳的酸洗性能(速度和空间),请在HIGHEST_PROTOCOL处使用cPickle

使用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

相关问题 更多 >