【问题标题】:Writing a 2-D List to a File, Reading it out and Re-Using saved List将二维列表写入文件,读出并重新使用保存的列表
【发布时间】:2019-01-18 18:48:29
【问题描述】:

我想将二维数组写入 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]"]

还有其他精彩的结果。 有谁知道这个或教程的一些简单直接的代码? 只是出于好奇而这样做,tbh并且正在努力挣扎。

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

【问题讨论】:

  • 你能发布一些你试过的代码吗?然后,我们可以为您指出您可能走错路的地方......
  • @LoosaBway “我希望能够再次从文件中读取我的列表并再次将其完全用作列表”问题是您只是将列表的字符串表示形式写入一个文件,并调用该序列化。正如此处的其他答案所建议的那样,您应该简单地使用一种内置的序列化格式,JSON、YAML、pickle(尚未提及)。否则,您必须自己解析字符串表示。重要的一点是您保存在文件中的内容不是列表

标签: python list file text


【解决方案1】:

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 文本文件指令倾向于向保存/检索的内容添加语音标记所带来的困难,我我想,我想解决这个问题,只是为了它。
【解决方案2】:

还要考虑 yaml。需要安装 pyyaml (pip 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)


要直接处理字符串,您可以使用标准库ast.literal_eval,这是一个简单的示例,您可以进一步自定义。
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())

【讨论】:

  • 我真的很想克服仅使用字符串和文件读取方法的挑战 - 处理各种语音标记似乎是如此困难的事情
  • 如果我明白你的意思,我在我的帖子中添加了一个编辑。您需要将 e 字符串解释为不同的对象(在本例中为列表),因此,您可以查看 docs.python.org/3/library/ast.html
【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-31
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多