Python save list and read data from file

python

Solution

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.

Problem

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

Original source

Related problems