简体   繁体   中英

python how to store a list in a file and get it back

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" ) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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