[英]While reading txt file lines. I can't “append list” or “update dictionary” why?
I have txt file like that:我有这样的txt文件:
"aroint" : "Lorem.",
"agama" : "Simply.",
"allantoidea" : "Dummy.",
"ampelopsis" : "Whiske"\"red.",
"zopilote" : "Vulture.\n\n",
"zooedendrium" : "Infusoria."
I tried to read the txt file, convert Python dictionary and then create the json file我尝试读取txt文件,转换Python字典,然后创建json文件
import json
dictionary = {}
with open('/Users/stackoverflowlover/Desktop/source.txt', "r") as f:
for line in f:
s = (line.replace("\"", "").replace("\n\n", "").replace("\n", "").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)
print(json.dumps(dict, sort_keys=True, indent=4))
My output:我的 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?
我该如何解决?
Here you go.这里是 go。 below logic will read you file and convert it to the JSON structure which you are looking as output
下面的逻辑将读取您的文件并将其转换为您正在查看的 JSON 结构 output
import re
import json
f = open("/Users/stackoverflowlover/Desktop/source.txt", "r")
data = {}
for line in f:
line = line.split(":")
line[0] = re.sub("[^\w]+", "", line[0])
line[1] = re.sub("[^\w]+", "", line[1])
data[line[0]] = line[1]
print(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.