![](/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.