【问题标题】:How to convert a txt file to a Json file? with python 2.7如何将txt文件转换为Json文件?使用 python 2.7
【发布时间】: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


【解决方案1】:

好的,完成。 .完成

import csv
import json
import pandas as pd

df = pd.read_csv("joko.txt",sep=" ",header=0,names=["Name", "Age", "Gender", 
"Location"])
df.to_csv("joko.csv", index=False)
print(df.head)

file = 'joko.csv'
json_file = 'joko.json'
fieldnames = ("Name", "Age", "Gender", "Location")

    
##Read CSV File
def read_CSV(file, json_file):
csv_rows = []
with open(file) as csvfile:
    reader = csv.DictReader(csvfile)
    field = reader.fieldnames
    for row in reader:
        csv_rows.extend([{field[i]:row[field[i]] for i in range(len(field))}])
        convert_write_json(csv_rows, json_file)
 print("Membaca File CSV")

 ##Convert csv data into json
 def convert_write_json(data, json_file):
 with open(json_file, "w") as f:
    f.write(json.dumps(data, sort_keys=False, indent=10, separators=(',', ': '))) 
 print("FINISH")


 read_CSV(file,json_file)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多