私はプログラミングを始めたばかりで、過去3/4週間からpythonを学んでいます。これは与えられた課題の1つです。
入力
A, B, C, D
1, 2, 3, 4
5, 6, 7, 8
出力
{{A:"1", B:"2", C:"3", D:"4"}, {A:"5", B:"6", C:"7", D:"8"}}
私はコードを次のように試しています:
import csv
import json
csvfile = open('test.csv','r')
jsonfile = open('test.json','w')
x = ("a","b","c","d")
reader = csv.DictReader(csvfile, x)
for row in reader:
json.dump(row, jsonfile)
このコードの出力は次のとおりです。
{"a": "1", "null": ["5", "6", "7", "8", "9"], "c": "3", "b": "2", "d": "4"}
誰もこれで私を助けることができますか?
行全体を処理した後にダンプします。
import csv
import json
with open('test.csv') as f:
reader = csv.DictReader(f)
rows = list(reader)
with open('test.json', 'w') as f:
json.dump(rows, f)
ワンライナーが好きな人向け:
import csv
import json
json_data = [json.dumps(d) for d in csv.DictReader(open('file.csv'))]
実際の例については、このフィドルを確認してください: https://pyfiddle.io/fiddle/5992b8f4-552f-4970-91b6-a52cdee16ebc/?i=true
CSVをJson Pythonに変換する
import csv
import urllib2
url = '<YOURCSVURL>'
response = urllib2.urlopen(url)
cr = csv.reader(response)
line = {}
data = []
for index, row in enumerate(cr):
if index:
for index, col in enumerate(row):
line[name[index]] = col
data.append(line.copy())
else:
name = row
print data
import csv
import json
# Constants to make everything easier
CSV_PATH = './csv.csv'
JSON_PATH = './json'
# Reads the file the same way that you did
csv_file = csv.DictReader(open(CSV_PATH, 'r'))
# Created a list and adds the rows to the list
json_list = []
for row in csv_file:
json_list.append(row)
# Writes the json output to the file
file(JSON_PATH, 'w').write(json.dumps(json_list))