How to save a list to a file and read it as a list type?
You can use the pickle
module for that.
This module has two methods,
- Pickling(dump): Convert Python objects into a string representation.
- Unpickling(load): Retrieving original objects from a stored string representation.
https://docs.python.org/3.3/library/pickle.html
Code:
>>> import pickle
>>> l = [1,2,3,4]
>>> with open("test", "wb") as fp: #Pickling
... pickle.dump(l, fp)
...
>>> with open("test", "rb") as fp: # Unpickling
... b = pickle.load(fp)
...
>>> b
[1, 2, 3, 4]
Also Json
- dump/dumps: Serialize
- load/loads: Deserialize
https://docs.python.org/3/library/json.html
Code:
>>> import json
>>> with open("test", "w") as fp:
... json.dump(l, fp)
...
>>> with open("test", "r") as fp:
... b = json.load(fp)
...
>>> b
[1, 2, 3, 4]
I decided I didn't want to use a pickle because I wanted to be able to open the text file and change its contents easily during testing. Therefore, I did this:
score = [1,2,3,4,5]
with open("file.txt", "w") as f:
for s in score:
f.write(str(s) +"\n")
score = []
with open("file.txt", "r") as f:
for line in f:
score.append(int(line.strip()))
So the items in the file are read as integers, despite being stored to the file as strings.