[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 whilst 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:

score=[1,2,3,4,5]

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]


print(score)

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

This question is related to python list file python-3.x pickle

The answer is


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

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

https://docs.python.org/3.3/library/pickle.html

Code:

>>> import pickle
>>> l = [1,2,3,4]
>>> with open("test.txt", "wb") as fp:   #Pickling
...   pickle.dump(l, fp)
... 
>>> with open("test.txt", "rb") as fp:   # Unpickling
...   b = pickle.load(fp)
... 
>>> b
[1, 2, 3, 4]

Also Json

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

https://docs.python.org/3/library/json.html

Code:

>>> import json
>>> with open("test.txt", "w") as fp:
...     json.dump(l, fp)
...
>>> with open("test.txt", "r") as fp:
...     b = json.load(fp)
...
>>> b
[1, 2, 3, 4]

Although the accepted answer works, you should really be using python's json module:

import json

score=[1,2,3,4,5]

with open("file.json", 'w') as f:
    # indent=2 is not needed but makes the file human-readable
    json.dump(score, f, indent=2) 

with open("file.json", 'r') as f:
    score = json.load(f)

print(score)

Advantages:

  1. json is a widely adopted and standardized data format, so non-python programs can easily read and understand the json files
  2. json files are human-readable
  3. Any nested or non-nested list/dictionary structure can be saved to a json file (as long as all the contents are serializable).

Disadvantages:

  1. The data is stored in plain-text (ie it's uncompressed), which makes it a slow and bloated option for large amounts of data (ie probably a bad option for storing large numpy arrays, that's what hdf5 is for).
  2. The contents of a list/dictionary need to be serializable before you can save it as a json, so while you can save things like strings, ints, and floats, you'll need to write custom serialization and deserialization code to save objects, classes, and functions

When to use json vs pickle:

  • If you want to store something you know you're only ever going to use in the context of a python program, use pickle
  • If you need to save data that isn't serializable by default (ie objects), save yourself the trouble and use pickle.
  • If you need a platform agnostic solution, use json
  • If you need to be able to inspect and edit the data directly, use json

Common use cases:

  • Configuration files (for example, node.js uses a package.json file to track project details, dependencies, scripts, etc ...)
  • Most REST APIs use json to transmit and receive data
  • Data that requires a nested list/dictionary structure, or requires variable length lists/dicts
  • Can be an alternative to csv, xml or yaml files

pickle and other serialization packages work. So does writing it to a .py file that you can then import.

>>> score = [1,2,3,4,5]
>>> 
>>> with open('file.py', 'w') as f:
...   f.write('score = %s' % score)
... 
>>> from file import score as my_list
>>> print(my_list)
[1, 2, 3, 4, 5]

If you want you can use numpy's save function to save the list as file. Say you have two lists

sampleList1=['z','x','a','b']
sampleList2=[[1,2],[4,5]]

here's the function to save the list as file, remember you need to keep the extension .npy

def saveList(myList,filename):
    # the filename should mention the extension 'npy'
    np.save(filename,myList)
    print("Saved successfully!")

and here's the function to load the file into a list

def loadList(filename):
    # the filename should mention the extension 'npy'
    tempNumpyArray=np.load(filename)
    return tempNumpyArray.tolist()

a working example

>>> saveList(sampleList1,'sampleList1.npy')
>>> Saved successfully!
>>> saveList(sampleList2,'sampleList2.npy')
>>> Saved successfully!

# loading the list now 
>>> loadedList1=loadList('sampleList1.npy')
>>> loadedList2=loadList('sampleList2.npy')

>>> loadedList1==sampleList1
>>> True

>>> print(loadedList1,sampleList1)

>>> ['z', 'x', 'a', 'b'] ['z', 'x', 'a', 'b']

If you don't want to use pickle, you can store the list as text and then evaluate it:

data = [0,1,2,3,4,5]
with open("test.txt", "w") as file:
    file.write(str(data))

with open("test.txt", "r") as file:
    data2 = eval(file.readline())

# Let's see if data and types are same.
print(data, type(data), type(data[0]))
print(data2, type(data2), type(data2[0]))

[0, 1, 2, 3, 4, 5] class 'list' class 'int'

[0, 1, 2, 3, 4, 5] class 'list' class 'int'


errorlist = ['aaaa', 'bbbb', 'cccc', 'dddd']

f = open("filee.txt", "w")
f.writelines(nthstring + '\n' for nthstring in errorlist)

f = open("filee.txt", "r")
cont = f.read()
contentlist = cont.split()
print(contentlist)

What I did not like with many answers is that it makes way too many system calls by writing to the file line per line. Imho it is best to join list with '\n' (line return) and then write it only once to the file:

mylist = ["abc", "def", "ghi"]
myfile = "file.txt"
with open(myfile, 'w') as f:
    f.write("\n".join(mylist))

and then to open it and get your list again:

with open(myfile, 'r') as f:
    mystring = f.read()
my_list = mystring.split("\n")

I am using pandas.

import pandas as pd
x = pd.Series([1,2,3,4,5])
x.to_excel('temp.xlsx')
y = list(pd.read_excel('temp.xlsx')[0])
print(y)

Use this if you are anyway importing pandas for other computations.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to pickle

Not able to pip install pickle in python 3.6 Python - AttributeError: 'numpy.ndarray' object has no attribute 'append' installing cPickle with python 3.5 How to read pickle file? What causes the error "_pickle.UnpicklingError: invalid load key, ' '."? How to save a list to a file and read it as a list type? ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle? Dump a list in a pickle file and retrieve it back later How to unpack pkl file? Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?