Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的Json文件-输出摘要_Python_Json_Python 3.x - Fatal编程技术网

Python中的Json文件-输出摘要

Python中的Json文件-输出摘要,python,json,python-3.x,Python,Json,Python 3.x,我在Python3中得到一个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

我在Python3中得到一个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来完成它

我认为您有语法错误。我运行了它,必须修复代码的第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

“不会在输出文件中打印”是什么意思?CSV输出文件为空?您是否检查了
结果
是否为空?您的数据是什么样子的?如果这解决了您的问题,请将其标记为解决方案。