python – How to save a list to a file and read it as a list type?
python – 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 didnt 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.
python – How to save a list to a file and read it as a list type?
Although the accepted answer works, you should really be using pythons 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:
json
is a widely adopted and standardized data format, so non-python programs can easily read and understand the json filesjson
files are human-readable- Any nested or non-nested list/dictionary structure can be saved to a
json
file (as long as all the contents are serializable).
Disadvantages:
- The data is stored in plain-text (ie its uncompressed), which makes it a slow and bloated option for large amounts of data (ie probably a bad option for storing large numpy arrays, thats what
hdf5
is for). - 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, youll need to write custom serialization and deserialization code to save objects, classes, and functions
Which one should I use?:
- If you want to store something you know youre only ever going to use in the context of a python program, use
pickle
- If you need to save data that isnt 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 of json
:
- Configuration files (for example,
node.js
uses apackage.json
file to track project details, dependencies, scripts, etc …) - Most
REST
APIs usejson
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
oryaml
files