python如何将列表存储在文件中并取回 [英] python how to store a list in a file and get it back
本文介绍了python如何将列表存储在文件中并取回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有很多东西的清单.在脚本的最后,我想将其存储在文件中.
当我第二天启动另一个脚本时,我想从文件中提取列表,然后使用它.
我不知道这是否是最好的方法.
I have a list with a lot of things in.
At the end of my script I would like to store it in a file.
And when I start another script another day, I would like to extract my list from my file and then use it.
I don't know if it's the best way to do this.
这就是我想用代码"为那些不懂的人做的事情
Here is what i would like to do in "code" for those who didn't understand
#script1
l = ('hey', 'ho', 'hello', 'world')
#save list into myfile
#script2
l = getmylistfrommyfile()
print(l)
>>>('hey', 'ho', 'hello', 'world')
#I can now use my list !
推荐答案
If you are looking for the best and most pythonic way of doing this then Pickling is a better idea. It is as simple as :
#Save a dictionary into a pickle file.
import pickle
favorite_color = { "lion": "yellow", "kitty": "red" }
pickle.dump( favorite_color, open( "save.p", "wb" ) )
# Load the dictionary back from the pickle file.
favorite_color = pickle.load( open( "save.p", "rb" ) )
这篇关于python如何将列表存储在文件中并取回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文