将2D列表写入文件,读取并重用保存的Lis

2024-10-06 11:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个二维数组到一个python3txt文件

例如

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

进入myu text.txt

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

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

和字符串列表:

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

以及其他精彩的结果。 有人知道一些简单明了的代码吗? 只是出于好奇,我很努力

我想能够读出我的清单从文件中再次和充分利用它作为一个清单再次 e、 g,print(my_list[0][0])产生'Hello'


Tags: 文件方法texttxt元素hello列表world
3条回答

嗨,有兴趣的人

我想将一个数组保存到一个Python文本文件中并完全检索它,这样就可以处理所有元素

我坚持我的问题,并解决了什么是非常混乱的代码,我敢肯定

下面的代码就是我想做的

毫无意义的运动,但我不得不这么做

谢谢你的帮助和想法

my_list = []
my_list_669 = []

def create_list():
    #Creating the list

    for x in range(5):
        my_list.append(["Hello", "World", x])

    print("my_list = ", my_list)


def save_list_to_file():
    #creating the string

    string_1 = ""

    for item in my_list:
        string = item[0] + "," + item[1] + "," + str(item[2]) + "\n"
        string_1 += string
        #adds records to a string with a line return after each record

    with open('your_file.txt', 'w') as f:
            f.write(string_1)


def recover_list():

    with open('your_file.txt', 'r') as f:
            tiing = f.read().splitlines()
            #splits lines at \n and inserts into array called 'tiing'
            #each item is equivalent to a record

    for items1 in tiing:
        my_list_69 = items1.split(",")
        #splits the array items in ting at "," mark
        #these are now in an array called 'my_list_69'
        #below I access all items from within the list
        #and append them to a temporary sub-list

        sub_list = []
        for items in my_list_69:
            sub_list.append(items)

        my_list_669.append(sub_list)  this reconstructs the list


create_list()
save_list_to_file()
recover_list()

Testing:
print(my_list_669)
print(my_list_669[0])
print(my_list_669[0][2])
for items in my_list_669:
    print(items)

同时考虑yaml。需要安装pyyamlpip install pyyaml

import yaml

将列表对象保存到文件:

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

with open('my_list.yml', 'w') as outfile:
    yaml.dump(my_list, outfile, default_flow_style=False)

输出文件如下所示:

- - Hello
  - World
  - 0
- - Pretty
  - World
  - 1
- - Tired
  - World
  - 2

要加载列表:

with open("my_list.yml", 'r') as inputfile:
    my_list_back = yaml.load(inputfile)


要直接处理字符串,可以使用标准库^{},这是一个简单的示例,您可以进一步自定义。
import ast

string_list = (str(my_list)) # convert tostring then save it to file
print(string_list.__class__) # it's a string
reconverted_list = ast.literal_eval(string_list) # convert back with ast
print(reconverted_list.__class__) # it's a list

而不是基本的读/写:

with open('my_list.txt', 'w') as file:
    file.write(str(my_list))

with open('my_list.txt', 'r') as file:
    my_list_back = ast.literal_eval(file.read())

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]]

相关问题 更多 >