Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

python - While reading txt file lines. I can't "append list" or "update dictionary" why?

I have txt file like that:

"aroint" : "Lorem.",
"agama" : "Simply.",
"allantoidea" : "Dummy.",
"ampelopsis" : "Whiske""red.",
"zopilote" : "Vulture.

",
"zooedendrium" : "Infusoria."

I tried to read the txt file, convert Python dictionary and then create the json file

import json
dictionary = {}
with open('/Users/stackoverflowlover/Desktop/source.txt', "r") as f:
    for line in f:
        s = (line.replace(""", "").replace("

", "").replace("
", "").strip().split(":"))
        xkey = (s[0])
        xvalue = (s[-1])
        zvalue = str(xvalue)
        value = zvalue[:0] + zvalue[0 + 1:]
        key = xkey.replace(' ', '', 1)
        dict = {'key1': 'stackoverflow'}
        dictadd={key:value}
        (dict.update(dictadd))
        dictionary_list = []
        dictionary_list.append(key)
        dictionary_list.append(value)
        
print(dictionary_list)
with open("/Users/stackoverflowlover/Desktop/test.json", 'w', encoding='utf8') as f3:
  json.dump(dict, f3, ensure_ascii=False, indent=1)
  my_dict = json.dumps(dict, ensure_ascii=False)
print(json.dumps(dict, sort_keys=True, indent=4))

My output:

['zooedendrium', 'Infusoria.']
{
    "key1": "stackoverflow",
    "zooedendrium": "Infusoria."
}

When I try to read lines I can see all of them, but after I can see just the last lines dictionary. How I can fix that?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...