跳过csv中的标题行

时间:2019-09-12 23:36:39

标签: json csv python-3.7

我正在将csv转换为文件json,并尝试跳过前5个标头行 一个示例文件:

No errors               
No warnings             
646 ms              
data source=metars              
4797 results                
raw_tex station_id  observation_time    latitude    longitude
stuff   KJES            2019-09-12T22:21:00Z    31.55           -81.88
stuff   KRQB            2019-09-12T22:20:00Z    43.72           -85.5
stuff   LATI            2019-09-12T22:20:00Z    41.42           19.72
stuff   KSTK            2019-09-12T22:20:00Z    40.62           -103.27

代码:

import csv, json

csvFilePath = "metars.csv"
jsonFilePath = 'metars.json'

data = {}
with open(csvFilePath) as csvFile:
    csvReader = csv.DictReader(csvFile)
    for csvRow in csvReader:
        icao = csvRow['station_id']
        data[icao] = csvRow

with open(jsonFilePath, 'w') as jsonFile:
    jsonFile.write(json.dumps(data, indent=4))

错误: 由于标题行,它给出了一个关键错误

如果我删除标题行,则转换正常。

1 个答案:

答案 0 :(得分:0)

您可以在创建阅读器之前自行跳过以下行:

with open(csvFilePath) as csvFile:
    for _ in range(5):
        csvFile.readline()
    csvReader = csv.DictReader(csvFile)