我试图从csv转换到json,它给出了一个错误,因为reader_row[10]
有缺失的值。我如何将缺失的值替换为Null?和写作。
l = []
with open("data.csv", 'r') as data_file:
reader = csv.reader(data_file)
headers = next(reader)
for reader_row in reader:
d = {}
d[headers[11]] = str(reader_row[11])
d[headers[13]] = str(reader_row[13])
d[headers[14]] = str(reader_row[14])
d[headers[18]] = str(reader_row[18])
d[headers[3]] = int(reader_row[3])
d[headers[16]] = bool(reader_row[16])
d[headers[4]] = float(reader_row[4])
d[headers[5]] = str(reader_row[5])
d[headers[10]] = int(reader_row[10])
d[headers[17]] = int(reader_row[17])
d[headers[15]] = int(reader_row[15])
d[headers[0]]={'Address Street': str(reader_row[0]),
'Address City': str(reader_row[1]),
'Address Postcode': str(reader_row[2])
}
d[headers[8]]={'Credit Card Number': str(reader_row[8]),
'Credit Card Start Date': str(reader_row[6]),
'Credit Card Expiry Date': str(reader_row[7]),
'Credit Card CVV': int(reader_row[9]),
'Bank IBAN' : str(reader_row[12])
}
d[headers[19]]={'Vehicle Make': str(reader_row[19]),
'Vehicle Model': str(reader_row[20]),
'Vehicle Year': int(reader_row[21]),
'Vehicle Type': str(reader_row[22])
}
l.append(d)
如果reader_row[10]
为空,可以使用条件运算符将None
赋值。
d[headers[10]] = int(reader_row[10]) if reader_row[10] else None