如何使我的代码创建一个存储变量的文件,然后再从文件中读取变量,以便它们在我的代码中可用。
我该怎么做?
import pickle
以下是一些示例数据:
key_value_mapping = dict(tuple=(), string='', list=[], int=0, set=set())
提供您希望文件存在的路径,例如:
file_location= '/temp/foobar'
我们需要打开一个文件,以将(w)写入二进制(b)文件(请参阅'wb'
传递给open函数的标志)。这两行演示了如何执行此操作:
with open(file_location, 'wb') as file:
pickle.dump(key_value_mapping, file)
最后,我们需要打开文件以将其读为二进制文件(b),然后检索数据:
with open(file_location, 'rb') as file:
data = pickle.load(file)
print(data)
{'tuple': (), 'set': set(), 'int': 0, 'list': [], 'string': ''}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句