如何将列表保存到文件并将其作为列表类型读取?

新手上路,请多包涵

假设我有列表 score = [1,2,3,4,5] 并且它在我的程序运行时发生了变化。我怎样才能将它保存到一个文件中,以便下次运行程序时,我可以访问更改后的列表作为 list 类型?

我试过了:

 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)

但这会导致列表中的元素是字符串而不是整数。

原文由 Oceanescence 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 280
2 个回答

我决定不想使用泡菜,因为我希望能够在测试期间轻松打开文本文件并更改其内容。因此,我这样做了:

 score = [1,2,3,4,5]

with open("file.txt", "w") as f:
    for s in score:
        f.write(str(s) +"\n")

 score = []
with open("file.txt", "r") as f:
  for line in f:
    score.append(int(line.strip()))

所以文件中的项目被读取为整数,尽管作为字符串存储到文件中。

原文由 Oceanescence 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以为此使用 pickle 模块。这个模块有两种方法,

  1. Pickling(dump) :将 Python 对象转换为字符串表示形式。
  2. Unpickling(load) :从存储的字符串表示中检索原始对象。

https://docs.python.org/3.3/library/pickle.html

代码

 >>> import pickle
>>> l = [1,2,3,4]
>>> with open("test", "wb") as fp:   #Pickling
...   pickle.dump(l, fp)
...
>>> with open("test", "rb") as fp:   # Unpickling
...   b = pickle.load(fp)
...
>>> b
[1, 2, 3, 4]


还有杰森

  1. 转储/转储:序列化
  2. 加载/加载:反序列化

https://docs.python.org/3/library/json.html

代码

 >>> import json
>>> with open("test", "w") as fp:
...     json.dump(l, fp)
...
>>> with open("test", "r") as fp:
...     b = json.load(fp)
...
>>> b
[1, 2, 3, 4]

原文由 Vivek Sable 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题