How do I save a list in a file and read it as a list type?
source link: https://www.codesd.com/item/how-do-i-save-a-list-in-a-file-and-read-it-as-a-list-type.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How do I save a list in 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.
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]
Related Articles
save Btrees to a disk file and read it
How to create a html form after downloading files and reading the json response from the php server
Java - How can I write my ArrayList to a file, and read (load) this file in the original ArrayList?
How can I store the dictionaries in a file and read / write this file?
How do I save an object in the file?
How to compare an object list type with the type of int list
How do I get data from a text file and save it in a string?
How to write OrderedDicts to a file and read it in a list?
How do I save an image or text file for later use?
How do I save an object to a file?
How to use Javascript to read the local text file and read line by line?
Are there any Java virtual machines that can save their state to a file and reload that state?
How do I save a list of objects in Redis using a single key-value?
How do I save a list to a .py file?
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK