打开pickle文件并添加到它们

时间:2014-08-02 22:11:01

标签: python-2.7 object pickle

我正在尝试将信息存储在pickle文件中,然后不断地将新信息附加到此文件,而不会覆盖任何信息。这里唯一的问题是,如果我关闭程序并重新运行它创建一个新对象并将其保存到输出中覆盖以前的信息,相当确定有一个简单的解决方案。我的代码看起来像这样:

#save object to file function
def save_object(obj, filename):
  with open(filename, 'wb') as output:
    pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)


#Add employee to dict, increment id
def add_employee(self,employee):
  self.employee_dict[self.employee_id] = employee
  employee.id = self.employee_id
  self.employee_id += 1


#Get object info, call add_employee, save object
employee = Employee.from_input()
self.add_employee(employee)                    
Employee.save_object(self.employee_dict, r'Obj_file.pkl')

编辑:要加载我正在使用的文件:

elif self.menu_select == 5:
  self.load_file = open("Obj_file.pkl", 'rb+')
  self.employee_dict = pickle.load(self.load_file)
  print self.employee_dict

1 个答案:

答案 0 :(得分:0)

使用追加模式:

  with open(filename, 'wb') as output:

=>

  with open(filename, 'ab') as output:

否则每次都会重写文件。