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 c
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.
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]
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")