gpt4 book ai didi

python - 将二维列表写入文件、读出并重新使用保存的列表

转载 作者:行者123 更新时间:2023-12-01 01:16:54 25 4
gpt4 key购买 nike

我想将二维数组写入 Python 3 txt 文件。

例如

 My_list = ['Hello', 'World', 0], ['Pretty', 'World', 1], ['Tired', 'World', 2]]

进入 my_text.txt。

我尝试了很多方法,但没有一个是我可以推荐的,因为我得到了各种结果,包括 1 个元素列表:

["['Hello', 'World', 0], ['Pretty', 'World', 1], ['Tired', 'World', 2]"]

和字符串列表:

["[Hello', 'World', 0]", "['Pretty', 'World', 1]", "['Tired', 'World', 2]"]

还有其他精彩的结果。有谁知道一些简单直接的代码或教程?只是出于好奇才这样做,说实话,我正在苦苦挣扎。

我希望能够再次从文件中读取我的列表,并再次将其完全用作列表例如, print(my_list[0][0]) 产生 'Hello'

最佳答案

json 擅长序列化列表/字典/数字/字符串:

import json 

My_list = [['Hello', 'World', 0], ['Pretty', 'World', 1], ['Tired', 'World', 2]]

#write to file
with open("data.json", "w") as file:
json.dump(My_list, file)

#read from file
with open("data.json") as file:
new_list = json.load(file)

print(new_list)

结果:

[['Hello', 'World', 0], ['Pretty', 'World', 1], ['Tired', 'World', 2]]

关于python - 将二维列表写入文件、读出并重新使用保存的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54259833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com