Python中的Json文件-输出摘要

时间:2018-09-27 19:41:47

标签: python json python-3.x

我在python 3中得到一个json文件,必须对其进行排序。我正确地完成了所有操作,但不会将其打印到输出文件中。

import json
from collections import defaultdict
import csv
from operator import itemgetter
#Source - youtube.com/thenewboston - Bucky Roberts

# load data from json file
with open('makes.json') as f:
    data = json.load(f)

# dictionary to hold items
countries_makes = defaultdict(int)
countries_common = defaultdict(int)

# loop through data (json object with data in an array 'Makes')
for m in data['Makes']:
    # grab the country
    country = m['make_country']
    countries_makes[country] += 1
    is_common = int(m['make_is_common'])
    countries_common[country] += is_common

# put data in a list
result = []
for c in countries_makes:
    # each item in the list will contain: (country, makes, common)
    result.append((c, countries_makes[c], countries_common[c]))

# sort result list by make in reverse order
result.sort(key=itemgetter(1), reverse=True)

# create output file with headers and rows
with open('summary.csv', 'wb') as f:
    csv_output = csv.writer(f)
    csv.writerow(['Country', 'Makes', 'Common'])
    csv_output.writerows(result)

print('done, see results in summary.csv')

那么我该如何做呢?问题结尾处带有空行。

我需要打开summary.csv来完成它。

1 个答案:

答案 0 :(得分:1)

我相信您有语法错误。我运行了它,必须修复您的代码的第35行。

csv.writerow() -> csv_output.writerow()

根据按键,我使用了以下数据:

{"Makes":[{"make_country":"countryA", "make_is_common":1}]}

将代码固定为:

# create output file with headers and rows
with open('summary.csv', 'wb') as f:
    csv_output = csv.writer(f)
    csv_output.writerow(['Country', 'Makes', 'Common'])
    csv_output.writerows(result)

生产:

$ cat summary.csv 
Country,Makes,Common
countryA,1,1