Tyson
最基本的方法是使用Pickle模块保存数据并将其加载到磁盘:
下面是我如何在一个简单的程序中使用它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()
赞踩评论- 7月29日 14:46