Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Save a list and recover it for AI learning application

I have an application that requires saving a list as it grows. This is a step towards doing AI learning stuff. Anyway here is my code:

vocab = ["cheese", "spam", "eggs"]

word = raw_input()

vocab.append(word)

However when the code is run the finished vocab will return to just being cheese, spam and eggs.
How can I make whatever I append to the list stay there permenantly even when windows CMD is closed and I return to the code editing stage. Is this clear enough?? Thanks

like image 216
RPGer Avatar asked Nov 20 '25 18:11

RPGer


2 Answers

You're looking into the more general problem of object persistence. There are bazillions of ways to do this. If you're just starting out, the easiest way to save/restore data structures in Python is using the pickle module. As you get more advanced, there are different methods and they all have their trade-offs...which you'll learn when you need to.

like image 71
parselmouth Avatar answered Nov 23 '25 06:11

parselmouth


You could use json and files, something like this:

import json

#write the data to a file
outfile = open("dumpFile", 'w')
json.dump(vocab, outfile)

#read the data back in
with open("dumpFile") as infile:
    newVocab = json.load(infile)

This has the advantage of being a plain text file, so you can view the data stored in it easily.

like image 24
kragniz Avatar answered Nov 23 '25 08:11

kragniz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!