Blo*_*ard 34 python persistence file
假设我有这样的事情:
d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }
Run Code Online (Sandbox Code Playgroud)
什么是最简单的方法,以程序方式将 其转换为我以后可以从python加载的文件?
我可以以某种方式将其保存为python源(从python脚本中,而不是手动!),然后import它呢?
或者我应该使用JSON还是其他什么?
eco*_*sis 61
使用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
Run Code Online (Sandbox Code Playgroud)
Mil*_*les 15
您可以选择:Python标准库 - 数据持久性.哪一个最合适可能因您的具体需求而异.
pickle 就"将任意对象写入文件并恢复它"而言,它可能是最简单和最有能力的 - 它可以自动处理自定义类和循环引用.
为了获得最佳的酸洗性能(速度和空间),使用cPickle在HIGHEST_PROTOCOL.
尝试搁置模块,它将为您提供持久字典,例如:
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]}
Run Code Online (Sandbox Code Playgroud)