简体   繁体   English

腌制清单-错误

[英]Pickling a list - error

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

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' . 如果您多次执行此操作,则此操作将失败,因为您是以'ab'模式而不是'wb'模式打开pickle文件。 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! 当您将元素添加到列表时,您实际上并没有附加到FILE,而是在更改对象本身! 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. 这意味着您需要完全更改文件中写入的内容,以便它使用附加的额外元素来描述此新对象。

You're iterating over the object returned by the load function and for some reason you're trying to access the object via indexes. 您正在迭代由load函数返回的对象,由于某种原因,您试图通过索引访问该对象。 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. Library[1]不存在,因此string index out of range错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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