【问题标题】:Skip header lines in csv跳过 csv 中的标题行
【发布时间】:2019-09-12 23:36:39
【问题描述】:

我正在将 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))

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

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

【问题讨论】:

    标签: json csv python-3.7


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 2013-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多