Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...