Simple questions for those who know, pretty hard for me, as I think that it is not pratically possible.
After making a simple python program, it is possible to run it on the computer's command prompt.
I was wondering or it is possible to allow someone who runs it that way, to add an element to a list (list.insert) and have it still there the next time the program is run?(thus editting the predefined list to a new list and saving it that way)
EDIT: just giving a bit more information:
All the program has to do is allow you to choose a list. From this list it returns a random item. I was just hoping to allow to add items to this list while running the program, keeping the list updated afterwards.
The most basic way is to use the Pickle module to save and load your data to disk:
http://docs.python.org/2/library/pickle.html
http://docs.python.org/2/library/pickle.html#example
Here's how I would use it in a simple program
try:
import cPickle as pickle
except ImportError:
import pickle
class MyClass(object):
def __init__(self, file_name):
self.array = []
self.file_name = file_name
self.load_data()
def add_element(self, element):
self.array.append(element)
self.save_data()
def load_data(self):
try:
with open(self.file_name, "r") as f:
self.array = pickle.load(f)
except IOError:
pass
def save_data(self):
with open(self.file_name, "w") as f:
pickle.dump(self.array, f)
def main():
FILE_NAME = "test.pkl"
a = MyClass(FILE_NAME)
print "elements in array are", a.array
for i in range(5):
a.add_element(i)
if __name__ == "__main__":
main()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.