1

I'm trying to make my program ask for input (for example a name) and save this name with pickle to a new line each time it is run to a text file. For example: If I wanted to save the name "John" the first time it would save on the first line "John", then the second time I ran the program, it would save the name "Jeff" on the second line and so on.

I've already imported and set up the asking for input and the part where pickle dumps it to a file.

import pickle

print("Hello!")
name = input("What is your name? : ")
print (name)
file1 = open("store.txt", "wb")
pickle.dump(name, file1)
file1.close()

It does save the input but every time I rerun the program and input a different string, it overwrites the previous one.

BPDESILVA
  • 2,040
  • 5
  • 15
  • 35
Simonas K
  • 23
  • 7
  • Possible duplicate of [python open built-in function: difference between modes a, a+, w, w+, and r+?](https://stackoverflow.com/questions/1466000/python-open-built-in-function-difference-between-modes-a-a-w-w-and-r) – manveti Jul 01 '19 at 23:40

2 Answers2

2

Use "ab+" instead of "wb" when opening the file to do it in append mode.

jacalvo
  • 656
  • 5
  • 14
0

When pickle opens a file with open(filename, 'wb'), it automatically wipes the contents of the file, similarly to how opening a text file with the 'w' argument will immediately wipe the contents.

You can open the file to read first, then save the contents of it, modify them or append your variables, then reopen the file with writing and save it. You could also use the 'ab' argument to open the file for appending. Either of those should work, but as-is the file is wiped with every open.

Sam Carpenter
  • 377
  • 3
  • 16