Я получаю json файл в python 3 и должен его сортировать. Я сделал все это правильно, но он не будет печататься в выходной файл.
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
result
не пустой? Как выглядят ваши данные?