当我试图修改我的列表然后加载它时,我收到错误说:
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
请建议解决方案 我的代码:
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])
答案 0 :(得分:1)
这与酸洗无关。我将编写新的示例代码,说明它无法正常工作的原因。
library = []
library.append("user_input_goes_here")
print(library[0])
# OUTPUT: "user_input_goes_here")
print(library[1])
# IndexError occurs here.
你只是在空列表中附加一件事。为什么你认为有两个要素? :)
如果您多次执行此操作,则会失败,因为您在模式'ab'
而不是'wb'
中打开了pickle文件。每次写信时都应该覆盖泡菜。
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"
这可能看似违反直觉,因为您已经&#34;追加&#34;列表,但请记住,一旦你腌制一个对象它不再是一个列表,它就是一个pickle文件。当您向列表中添加元素时,您实际上并未附加到FILE,而是您正在更改对象本身!这意味着你需要完全改变文件中写的内容,以便它附加额外的元素来描述这个新对象。
答案 1 :(得分:0)
您正在迭代load
函数返回的对象,并且由于某种原因您尝试通过索引访问该对象。变化:
for key in library:
print (library[0])
print (library[1])
为:
for key in library:
print key
Library[1]
不存在,因此string index out of range
错误。