【发布时间】:2020-07-27 17:52:23
【问题描述】:
如何创建脚本将 txt 文件转换为 Json 文件?使用 python 2.7
我有一个包含内容的 txt 文件:
Name Age Gender Location
Joko 18 Man Chicago
Panijem 25 Woman Texas
Tukiman 30 Man London
Saritem 45 Woman Madrid
我想把它改成json,
[
{
"Name": "Joko",
"Age": " 18 ",
"Gender": "Man ",
"Location": "Chicago"
},
{
"Name": "Panijem",
"Age": " 25 ",
"Gender": "Woman ",
"Location": "Texas"
},
{
"Name": "Tukiman",
"Age": " 30 ",
"Gender": "Man ",
"Location": "London"
},
{
"Name": "Saritem",
"Age": " 45 ",
"Gender": "Woman ",
"Location": "Madrid"
}
]
我尝试使用脚本,但结果不是我想要的
import json
filename ='joko.txt'
dict1 = {}
with open(filename) as fh:
for line in fh:
command, description = line.strip().split(None, 1)
dict1[command] = description.strip()
out_file = open("joko.json", "w")
json.dump(dict1, out_file, indent = 10, sort_keys = False, separators=(' ', ': ')) out_file.close()
输出错误:
[{
"Tukiman": "30 Man London",
"Saritem": "45 Woman Madrid",
"Joko": "18 Man Chicago",
"Name": "Age Gender Location",
"Panijem": "25 Woman Texas"
}]
【问题讨论】:
-
你试过什么?你写了什么代码?这段代码有什么问题?
-
我试过如果是行的形式,而不是列或表的形式,所以如果数据是表的形式,我很困惑。你能帮帮我吗?
标签: python-2.7