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.
I am using pandas.
Use this if you are anyway importing pandas for other computations.
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:
and then to open it and get your list again:
You can also use python's
json
module:The advantage of using a json is that:
Typically, you'll see jsons used for more complicated nested lists/dictionaries (like an array of records). The main disadvantage of storing your data as a json is that the data is stored in plain-text, and as such is completely uncompressed, making it a slow and bloated option for large amounts of data.
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:
So the items in the file are read as integers, despite being stored to the file as strings.
If you don't want to use pickle, you can store the list as text and then evaluate it:
If you want you can use numpy's save function to save the list as file. Say you have two lists
here's the function to save the list as file, remember you need to keep the extension .npy
and here's the function to load the file into a list
a working example