![](/img/trans.png)
[英]How can I add key values into a dictionary from reading in each line of a .txt file and update values?
[英]While reading txt file lines. I can't “append list” or “update dictionary” why?
我有这样的txt文件:
"aroint" : "Lorem.",
"agama" : "Simply.",
"allantoidea" : "Dummy.",
"ampelopsis" : "Whiske"\"red.",
"zopilote" : "Vulture.\n\n",
"zooedendrium" : "Infusoria."
我尝试读取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))
我的 output:
['zooedendrium', 'Infusoria.']
{
"key1": "stackoverflow",
"zooedendrium": "Infusoria."
}
当我尝试阅读行时,我可以看到所有行,但是在我只能看到最后一行字典之后。 我该如何解决?
这里是 go。 下面的逻辑将读取您的文件并将其转换为您正在查看的 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.