Reputation: 193
When I'm trying to amend my list and then load it, I get error saying:
Traceback (most recent 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 My code:
import pickle
library = []
with open ("LibFile.pickle", "ab") as lib:
user = input("give the number")
print ("Pickling")
library.append(user)
pickle.dump(user, lib)
lib.close()
lib = open("LibFile.pickle", "rb")
library = pickle.load(lib)
for key in library:
print (library[0])
print (library[1])
Upvotes: 0
Views: 388
Reputation: 54163
This has nothing to do with pickling. I'll write new sample code that shows why it 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 only appending one thing to your empty list. Why do you think there are two elements? :)
If you're doing this multiple times, it's failing because you're opening the pickle file in mode 'ab'
instead of 'wb'
. You should be overwriting the pickle each time you write to it.
import pickle
library = ["index zero"]
def append_and_pickle(what_to_append,what_to_pickle):
what_to_pickle.append(what_to_append)
with open("testname.pkl", "wb") as picklejar:
pickle.dump(what_to_pickle, picklejar)
# no need to close with a context manager
append_and_pickle("index one", library)
with open("testname.pkl","rb") as picklejar:
library = pickle.load(picklejar)
print(library[1])
# OUTPUT: "index one"
This may seem counter-intuitive since you're "appending" to the list, but remember that once you pickle an object it's not a list anymore, it's a pickle file. You're not actually appending to the FILE when you add an element to the list, you're changing the object itself! That means you need to completely change what's written in the file, so that it describes this new object with the extra element attached.
Upvotes: 1
Reputation: 8275
You're iterating over the object returned by the load
function and for some reason you're trying to access the object via indexes. Change:
for key in library:
print (library[0])
print (library[1])
to:
for key in library:
print key
Library[1]
doesn't exist, hence the string index out of range
error.
Upvotes: 0