这是将列表写入文件的最简洁方法,因为writelines()不插入换行符吗?
file.writelines(["%s\n" % item for item in list])
Run Code Online (Sandbox Code Playgroud)
似乎有一种标准方式......
假设我有列表得分= [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)
Run Code Online (Sandbox Code Playgroud)
但这会导致列表中的元素不是整数.