首页 > 解决方案 > 要列出的文件内容,但不是字符串

问题描述

我正在尝试将带有字典的嵌套列表从 txt 文件附加到新列表中。我所做的一切,内容总是成为新列表中的字符串。

是否可以按原样从文件中读取数据并将其附加到列表中,就像嵌套列表一样?

这是我的代码:

dataFile = "library.txt"

with open(dataFile) as myfile:
    data="".join(line.rstrip() for line in myfile)
    data2=data.replace(" ","")

    newLibraryList = []

    newLibraryList.append(data2)

print(newLibraryList)

library.txt 内容如下所示。

[
    {"name": "brick"}, 
    {"dim": "0.108"},
    {"lamdbaValue": "0.610"},
    {"zValue": "5.000"},
    {"fireValue": "A"}
],
[
    {"name": "brick"},
    {"dim": "0.108"},
    {"lamdbaValue": "0.800"},
    {"zValue": "5.400"},
    {"fireValue": "A"}
]

如果有人可以帮助我或指出我正确的方向,我真的很感激。

提前谢谢

标签: pythonpython-3.x

解决方案


您的文件的某些部分类似于 JSON - 问题是:总共是无效的JSON。

这个:

[
    {"name": "brick"}, 
    {"dim": "0.108"},
    {"lamdbaValue": "0.610"},
    {"zValue": "5.000"},
    {"fireValue": "A"}
]

对于包含 5 个字典(每个字典有 1 个键/值)的 1 元素列表是有效的 JSON。

下面的代码使用字符串拆分和魔法从您发布的演示数据中创建“有效”部分,然后使用JSON.loads(string)从中创建 python 对象。它很脆弱 - 如果您的文件中有任何错误,它将输出错误并跳过它。

它取决于拆分],- 如果您曾经在数据部分中添加这些拆分,它将破坏并且您必须修复它。

创建演示文件(一个数据集已损坏 - 丢失 } 等):

fn = "library.txt"

with open(fn,"w") as f:
    f.write("""[
    {"name": "brick"}, 
    {"dim": "0.108"},
    {"lamdbaValue": "0.610"},
    {"zValue": "5.000"},
    {"fireValue": "A"}
],
[
    {"name": "brick",
    {"dim": "0.108"},
    {"lamdbaValue": "0.800"},
    {"zValue": "5.400",
    {"fireValue": "A"}
],
[
    {"name": "brick"},
    {"dim": "0.108"},
    {"lamdbaValue": "0.800"},
    {"zValue": "5.400"},
    {"fireValue": "A"}
]""")

解析:

import json

lib = []

with open(fn,"r") as r:
    text = r.read()
    spl = [t.rstrip("]").replace(" ","").replace("\n"," ")+"]" for t in text.split("],")]

    parts = []
    for p in spl:
        try:
            parts.append(json.loads(p))
        except  json.JSONDecodeError  as e:
            print("Skipping: ", p)
            print(e)

    # parts = [json.loads(p) for p in spl] # removed list comp for better 
    # exception text output/messages

    lib.extend(parts)

for l in lib:
    print(l) 

输出:

Skipping:   [ {"name":"brick", {"dim":"0.108"}, {"lamdbaValue":"0.800"}, {"zValue":"5.400", {"fireValue":"A"} ]
Expecting property name enclosed in double quotes: line 1 column 21 (char 20)


[{'name': 'brick'}, {'dim': '0.108'}, {'lamdbaValue': '0.610'}, 
 {'zValue': '5.000'}, {'fireValue': 'A'}]

[{'name': 'brick'}, {'dim': '0.108'}, {'lamdbaValue': '0.800'}, 
 {'zValue': '5.400'}, {'fireValue': 'A'}]

将您的数据转换为有效的 json可能是值得的,这将大大简化:

fn = "library.txt"  # contains a list of dictionarys, each dict is one item

with open(fn,"w") as f:
    f.write("""[
    {"name": "brick", 
     "dim": "0.108",
     "lamdbaValue": "0.610",
     "zValue": "5.000",
     "fireValue": "A"}
,

    {"name": "brick",
     "dim": "0.108",
     "lamdbaValue": "0.800",
     "zValue": "5.400",
     "fireValue": "A"}
,   

    {"name": "brick",
     "dim": "0.108",
     "lamdbaValue": "0.800",
     "zValue": "5.400",
     "fireValue": "A"}
]""")

import json

lib = []

with open(fn,"r") as r:
    loaded_libs = json.load(r)

lib.extend(loaded_libs)

for l in lib:
    print(l) 

输出:

{'name': 'brick', 'dim': '0.108', 'lamdbaValue': '0.610', 
 'zValue': '5.000', 'fireValue': 'A'}
{'name': 'brick', 'dim': '0.108', 'lamdbaValue': '0.800', 
 'zValue': '5.400', 'fireValue': 'A'}
{'name': 'brick', 'dim': '0.108', 'lamdbaValue': '0.800', 
 'zValue': '5.400', 'fireValue': 'A'}

推荐阅读