How to save a list to a file and read it as a list type?
You can use pickle
module for that.This module have two methods,
- Pickling(dump): Convert Python objects into string representation.
- 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
- dump/dumps: Serialize
- 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]
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.
Although the accepted answer works, you should really be using python's json
module:
import jsonscore=[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 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). - 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
Which one should I use?:
- 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 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