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.
Method 2: write in a Text file In Python using writelines() The file is opened with the open() method in w mode within the with block, the argument will write text to an existing text file with the help of readlines(). The with block ensures that once the entire block is executed the file is closed automatically.
To read a file into a list in Python, use the file. read() function to return the entire content of the file as a string and then use the str. split() function to split a text file into a list. To read a file in Python, use the file.
You can read a text file using the open() and readlines() methods. To read a text file into a list, use the split() method.
You can use the pickle
module for that. This module has two methods,
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With