简体   繁体   English

python 3:将哈希存储在文件中并将其导入脚本

[英]python 3: storing a hash in a file and importing it into a script

I'm interested in Python 3 code that writes a hash to a disk file as a hash and then code that imports it into a script directly as a hash. 我对Python 3代码感兴趣,该代码将哈希值作为哈希值写入磁盘文件,然后将其直接作为哈希值导入到脚本中。

If importing wouldn't work then I'd be content to open and read a file, but I'd prefer not to have to rebuild a hash from a list every single time. 如果无法导入,那么我很乐意打开并读取文件,但我不想每次都不必从列表中重建哈希值。 I know that creating a list from a file is trivial, but searching a list is prohibitively slow in my script, so I want to use a hash because of the faster search. 我知道从文件创建列表很简单,但是在我的脚本中搜索列表的速度实在是太慢了,因此,由于搜索速度更快,我想使用哈希。 I don't actually need key-value pairs, just a list, and the hash would be purely to benchmark execution speeds at first. 实际上,我实际上不需要键值对,而只需要一个列表,散列起初纯粹是为了基准执行速度。 Thanks for all replies. 感谢您的所有回复。

In order to dump an object (such as a dictionary) into a file in a nice pythonic way, you can use the "pickle" module. 为了以一种很好的pythonic方式将对象(例如字典)转储到文件中,可以使用“ pickle”模块。 For example: 例如:

import pickle
mydic={"k1":[1,2,3],"k2":[6,6,6],"k3":"cats"}
f=open("./somefile.bin","wb")
pickle.dump(mydic,f)

You can then load the dumped object using pickel.load(), as described in the python docs (other options are specified as well): https://docs.python.org/2/library/pickle.html 然后,您可以使用pickel.load()加载转储的对象,如python docs中所述(还指定了其他选项): https ://docs.python.org/2/library/pickle.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM