I have a csv file like this:
Model 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Acura CSX/EL MDX NSX RDX RSX/Integra Other
Alfa Romeo 145/146/147 156/159 166 4C Brera GIULIETTA GTV/GT Mito Spider Other
Aston Martin DB7/DB9 DBS One-77 Rapide Vanquish Vantage Virage Zagato Other
Audi A1 A3 A4 A5 A6 A7 A8 Q3 Q5 Q7 R8 S3/RS3 S4/RS4 S5/RS5 S6/RS6 S7/RS7 S8
Where the first column is the model of a car, and the other columns are makes of that car.
The number of makes is dynamic. I want to save the makes for each car and tried to do it like this:
# -*- coding: utf-8 -*-
import csv
class CsvToJson:
def __init__(self, csvFilePath):
with open(csvFilePath, 'rU') as csvFile:
spamreader = csv.reader(csvFile, delimiter= ';',
quotechar = '|', dialect='excel')
final = dict()
for row in spamreader:
makes = list()
print ', '.join(row)
k = CsvToJson(csvFilePath = 'carsModelsMakes.csv')
But I am stuck about how to get the column.
after the great answer, i got this results
how can i remove these empty values please
You don't need a class to do this, just a function:
import csv
import json
def CsvToJson(csvFilePath):
with open(csvFilePath, 'rU', newline='') as csvFile:
final = {}
reader = csv.reader(csvFile, delimiter='\t') # change delimiter if needed
next(reader) # skip header
for row in reader: # now removes "empty" row values
final[row[0]] = [value for value in row[1:] if value]
return json.dumps(final, indent=4)
k = CsvToJson('carsModelsMakes.csv')
print(k)
Output:
{
"Acura": [
"CSX/EL",
"MDX",
"NSX",
"RDX",
"RSX/Integra",
"Other"
],
"Aston Martin": [
"DB7/DB9",
"DBS",
"One-77",
"Rapide",
"Vanquish",
"Vantage",
"Virage",
"Zagato",
"Other"
],
"Audi": [
"A1",
"A3",
"A4",
"A5",
"A6",
"A7",
"A8",
"Q3",
"Q5",
"Q7",
"R8",
"S3/RS3",
"S4/RS4",
"S5/RS5",
"S6/RS6",
"S7/RS7",
"S8"
],
"Alfa Romeo": [
"145/146/147",
"156/159",
"166",
"4C",
"Brera",
"GIULIETTA",
"GTV/GT",
"Mito",
"Spider",
"Other"
]
}
Try pandas
>>> import pandas as pd
>>> myFile = 'test.txt'
>>> df = pd.read_csv(myFile, sep=",", header=0)
>>> df
Model A B C
0 Model1 a b c
1 Model2 a b c
2 Model3 a b c
Getting the "Model" column
>>> df['Model']
0 Model1
1 Model2
2 Model3
Name: Model, dtype: object
Reformatting to JSON
>>> df['Model'].to_json()
'{"0":"Model1","1":"Model2","2":"Model3"}'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.