Python – How to save a list to a file and read it as a list type


Say I have the list score = [1,2,3,4,5] and it gets changed while my program is running. How could I save it to a file so that next time the program is run I can access the changed list as a list type?

I have tried:


with open("file.txt", 'w') as f:
    for s in score:
        f.write(str(s) + '\n')

with open("file.txt", 'r') as f:
    score = [line.rstrip('\n') for line in f]


But this results in the elements in the list being strings not integers.

Best Answer

You can use the pickle module for that. This module has two methods,

  1. Pickling(dump): Convert Python objects into a string representation.
  2. Unpickling(load): Retrieving original objects from a stored string representation.


>>> 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

  1. dump/dumps: Serialize
  2. load/loads: Deserialize


>>> 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]
Related Question