Monday, 15 April 2013

python - Pickling a list - error -



python - Pickling a list - error -

when i'm trying amend list , load it, error saying:

traceback (most recent phone call last): file "c:\users\t\desktop\pickle_process\pickle_process.py", line 16, in <module> print (library[1]) indexerror: string index out of range

please suggest solution code:

import pickle library = [] open ("libfile.pickle", "ab") lib: user = input("give number") print ("pickling") library.append(user) pickle.dump(user, lib) lib.close() lib = open("libfile.pickle", "rb") library = pickle.load(lib) key in library: print (library[0]) print (library[1])

this has nil pickling. i'll write new sample code shows why doesn't work.

library = [] library.append("user_input_goes_here") print(library[0]) # output: "user_input_goes_here") print(library[1]) # indexerror occurs here.

you're appending 1 thing empty list. why think there 2 elements? :)

if you're doing multiple times, it's failing because you're opening pickle file in mode 'ab' instead of 'wb'. should overwriting pickle each time write it.

import pickle library = ["index zero"] def append_and_pickle(what_to_append,what_to_pickle): what_to_pickle.append(what_to_append) open("testname.pkl", "wb") picklejar: pickle.dump(what_to_pickle, picklejar) # no need close context manager append_and_pickle("index one", library) open("testname.pkl","rb") picklejar: library = pickle.load(picklejar) print(library[1]) # output: "index one"

this may seem counter-intuitive since you're "appending" list, remember 1 time pickle object it's not list anymore, it's pickle file. you're not appending file when add together element list, you're changing object itself! means need alter what's written in file, describes new object element attached.

python pickle

No comments:

Post a Comment