文件内容列出,但不作为字符串

时间:2018-11-04 17:32:45

标签: python python-3.x

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

是否可以从文件中按原样读取数据并将其作为嵌套列表添加到列表中?

这是我的代码:

rename.tips <- function(phy, old_names, new_names) {
   mpos <- match(old_names,phy$tip.labels)
   phy$tip.labels[mpos] <- new_names
   return(phy)
}

library.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)

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

提前谢谢

1 个答案:

答案 0 :(得分:1)

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

此:

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

对于包含五个字典(每个字典具有一个键/值)的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'}