我希望获取一个包含数据的列表并附加它,以便下次执行代码时保存。到目前为止,我有这个工作,但当我再次执行代码时,它不包括输入的新数据。有什么建议吗?
def the_list():
data = ['data1', 'data2', 'data3 ' , 'data4', 'data5' ]
for i in data:
print (i)
print (' would you like to add')
a = input()
if a == ('yes'):
b = input()
data.append(b)
print (data)
the_list()
答案 0 :(得分:2)
如果你想在执行中保存数据,那么“实时”程序的内存中的所有内容在执行结束时都会被丢弃,所以你必须将数据保存到文件(或其他一些持久性介质),然后再读回来
您可以将文件另存为简单字符串,也可以使用pickle
轻松序列化列表等对象。
使用简单字符串
使用代码包装程序以将数据加载并保存到文件中:
data=[]
try:
old_data= open("save_data", "r").read().split('\n')
data.extend(old_data)
except:
print ("Unable to load old data!")
data = ['data1', 'data2', 'data3 ' , 'data4', 'data5' ]
#YOUR PROGRAM HERE
try:
with open("save_data", "w") as out:
out.write('\n'.join(data))
except:
print ("Unable to write data!")
当然,如果不能出现重复项,您必须做一些工作以防止data
中出现重复项。
使用pickle
import pickle
data_fn = "save_data"
data=[]
try:
with open(data_fn, "rb") as data_in:
old_data = pickle.load(data_in)
data.extend(old_data)
except:
print ("Unable to load last data")
data = ['data1', 'data2', 'data3 ' , 'data4', 'data5' ]
#REST OF YOUR PROGRAM
try:
with open(data_fn, "w") as data_out:
pickle.dump(data, data_out)
except:
print ("Unable to save data")
答案 1 :(得分:1)
def the_list():
try:
with open('data.txt', 'r') as f:
data = [line.strip() for line in f]
except:
data = []
for i in data:
print(i)
print (' would you like to add')
a = raw_input()
if a == 'yes':
b = input()
data.append(b)
print (data)
with open('data.txt', 'r') as nf:
nf.write('\n'.join(data))
the_list()
答案 2 :(得分:0)