4

Basically I would like to save a list to python and then when the program starts I would like to retrieve the data from the file and put it back into the list.
So far this is the code I am using

mylist = pickle.load("save.txt")
...
saveToList = (name, data)
mylist.append(saveList)
import pickle
pickle.dump(mylist, "save.txt")

But it just returns the following error: TypeError: file must have 'read' and 'readline' attributes

Octo
  • 695
  • 6
  • 20

3 Answers3

4

You need a file object, not just a file name. Try this for saving:

pickle.dump(mylist, open("save.txt", "wb"))

or better, to guarantee the file is closed properly:

with open("save.txt", "wb") as f:
    pickle.dump(mylist, f)

and then this for loading:

with open("save.txt", "rb") as f:
    mylist = pickle.load(f)

Also, I suggest a different extension from .txt, like maybe .dat, because the contents is not plain text.

Arthur Tacca
  • 8,833
  • 2
  • 31
  • 49
1
with open("save.txt", "w") as f:
    pickle.dump(f, mylist)

Refer to python pickle documentation for usage.

TurtleIzzy
  • 997
  • 7
  • 14
1

pickle.dump accept file object as argument instead of filename string

pickle.dump(mylist, open("save.txt", "wb"))
Skycc
  • 3,496
  • 1
  • 12
  • 18