简体   繁体   English

如何将腌制的数据附加到python中的文件?

[英]How to append a pickled data to a file in python?

import pickle

def user():
    name_input = raw_input("Name: ")
    age_input = raw_input("Age: ")
    email_input = raw_input("E-Mail: ")
    ph_input = raw_input("Phone Number: ")
    user_input = {'Name': name_input, 'Age': age_input, 'E-Mail': email_input, 'Phone number': ph_input}
    return user_input

a = user()
with open("picke.txt", "wb") as f:
    pickle.dump(a,f, pickle.HIGHEST_PROTOCOL)

b = "abc"
with open("picke.txt", "wb") as fi:
    pickle.dump(b,fi, pickle.HIGHEST_PROTOCOL)

When a file is opened, pickle dumped and closed.Again I open the same file to pickle.dump in it. 打开文件后,pickle将转储并关闭。再次我打开相同的文件将pickle.dump放入其中。 It does not append to the file but overwrites it. 它不会追加到文件中,但会覆盖它。 Any suggestions? 有什么建议么?

I was looking for the same problem, and the answer provided before did not work for me, using Python3.7 我一直在寻找相同的问题,使用Python3.7之前提供的答案对我不起作用

My solution is opening the file in 'ab' mode, use pickle to convert your object to binary ( pickle.dumps() not pickle.dump()) and write this to the file in a second step. 我的解决方案是在“ ab”模式下打开文件,使用pickle将对象转换为二进制文件( pickle.dumps()而不是pickle.dump()),然后将其写入文件。

with open('picke.txt', 'ab') as fi:
    bin_obj = pickle.dumps(obj)
    fi.write(bin_obj)

Hope this helps. 希望这可以帮助。

You are creating a new "picke.txt" with the lines: 您正在创建带有行的新“ picke.txt”:

with open("picke.txt", "wb") as fi:
    pickle.dump(a, f, pickle.HIGHEST_PROTOCOL)

You need to open in ab mode to append, not wb mode to write a new file as follows: 您需要以ab模式打开以进行追加,而不是wb模式以如下所示写入新文件:

with open("picke.txt", "ab") as fi:
    pickle.dump(a, f, pickle.HIGHEST_PROTOCOL)

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

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