【发布时间】:2015-02-28 23:34:18
【问题描述】:
假设我有列表 score=[1,2,3,4,5] 并且在我的程序运行时它会发生变化。如何将其保存到文件中,以便下次运行程序时可以将更改的列表作为列表类型访问?
我试过了:
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)
但这会导致列表中的元素是字符串而不是整数。
【问题讨论】:
-
听起来您可能对
pickle模块感兴趣。
标签: python list file python-3.x pickle