简体   繁体   中英

Python 3.6 - pickle

import pickle

randomlist = []
value = input("Add: ")
randomlist.append(value)
print(randomlist)

with open("randomlist_presistence.pkl", "wb") as pickle_out:
    pickle.dump(randomlist, pickle_out)

It creates a file called: "randomlost_presistence.pkl" and it has some symbols. But afterwards I don't know what should I do to unpickle the data. I don't know where to write this:

with open("randomlist_presistence.pkl", "rb") as pickle_in:
   randomlist = pickle.load(pickle_in)

My goal is to write something into the list and save it. Python 3.x. Thank you.

You can tests if the file exists then load it before you add extra elements. You can initialize the list as you did if the file does not exist.

import pickle
import os  # need os.path.isfile

if os.path.isfile("randomlist_presistence.pkl"):  # check if the file exists
    with open("randomlist_presistence.pkl", "rb") as pickle_in:  # here
        randomlist = pickle.load(pickle_in)

else:
    randomlist = []

value = input("Add: ")
randomlist.append(value)
print(randomlist)

with open("randomlist_presistence.pkl", "wb") as pickle_out:
    pickle.dump(randomlist, pickle_out)

You can read your pickle file in using the open function. In the example below x now contains your list read in from the pickle file.

with open('randomlist_presistence.pkl', 'rb') as f:
    x = pickle.load(f)

print(x)
['testing']

Pickle is a protocol to serialize data, that is to convert data to string. You can use this format to save python objects efficiently or to do some nice things like sending objects to different processes in RAM or to other nodes of a network. There is no a precise place in which you must load the file. Simply load it whenever you need (maybe in another program?)

You could use open from within pickle.load / pickle.dump . Here is an example:

import pickle

lst = [0, 1, 2, 3]

# save pickle file
pickle.dump(lst, open('file.pkl', 'wb'))

# load pickle file
x = pickle.load(open('file.pkl', 'rb'))  #  [0, 1, 2, 3]

# append item and save
x.append(4)
pickle.dump(x, open('file.pkl', 'wb'))

# reload pickle file
x = pickle.load(open('file.pkl', 'rb'))  #  [0, 1, 2, 3, 4]

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