简体   繁体   English

在新行 Python 中转储(泡菜)

[英]Dump (pickle) in new line Python

So i want to write each element of a list in a new line in a binary file using Pickle, i want to be able to access these dictionaries later as well.所以我想使用 Pickle 将列表的每个元素写入二进制文件的新行中,我希望以后也能够访问这些字典。

import pickle    
with open(r'student.dat','w+b') as file: 
for i in [{1:11},{2:22},{3:33},{4:44}]:
    pickle.dump(i,file)
file.seek(0)
print(pickle.load(file))

Output: Output:

{1: 11}

Could someone explain why the rest of the elements arent being dumped or suggest another way to write in a new line?有人可以解释为什么元素的 rest 没有被转储或建议另一种写新行的方法吗? I'm using Python 3我正在使用 Python 3

They're all being dumped, but each dump is separate;它们都被倾倒了,但每个倾倒都是分开的; to load them all, you need to match them with load calls.要全部加载它们,您需要将它们与load调用相匹配。

import pickle    
with open(r'student.dat','w+b') as file: 
    for i in [{1:11},{2:22},{3:33},{4:44}]:
        pickle.dump(i,file)
file.seek(0)
print(pickle.load(file))


import pickle    
with open(r'student.dat','w+b') as file: 
    for i in [{1:11},{2:22},{3:33},{4:44}]:
        pickle.dump(i,file)
file.seek(0)
for _ in range(4):
    print(pickle.load(file))

If you don't want to perform multiple loads, pickle them as a single data structure (eg the original list of dict s all at once).如果您不想执行多次加载,请将它们作为单个数据结构腌制(例如,一次全部dict的原始list )。

In none of these cases are you writing newlines, nor should you be;在这些情况下,您都没有写换行符,也不应该这样做; pickle is a binary protocol, which means newlines are just another byte with independent meaning, and trying to inject newlines into the stream would get in the way of loading the data, and risk splitting up bits of data (if you actually read a line at a time for loading). pickle 是一个二进制协议,这意味着换行符只是另一个具有独立含义的字节,尝试将换行符注入 stream 会妨碍加载数据,并有可能分割数据位(如果您实际上在加载时间)。

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

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