首页 > 解决方案 > 如何在python中读取时跳过csv文件中的标题行

问题描述

ValueError: invalid literal for int() with base 10: 'temperature(F)\n'

我想在阅读时跳过标题行,但我收到错误,因为它正在读取标题。

arr = []    
with open('D:\\ml_learning\\data-structures-algorithms-python-master\\data_structures\\4_HashTable_2_Collisions\\Solution\\nyc_weather.csv', 'r') as file:
    for line in file:
        tokens = line.split(',')
        try:
            temperature = int(tokens[1])
            arr.append(temperature)
        except Exception as e:
            print('invalid temperature'+e)

标签: python

解决方案


尝试使用file.readlines()然后将其切片以跳过第一行:

arr = []    
with open('D:\\ml_learning\\data-structures-algorithms-python-master\\data_structures\\4_HashTable_2_Collisions\\Solution\\nyc_weather.csv', 'r') as file:
    lines = file.readlines()
    for line in lines[1:]:
        tokens = line.split(',')
        try:
            temperature = int(tokens[1])
            arr.append(temperature)
        except Exception as e:
            print('invalid temperature'+e)

或者,看看 pandas 包,它专门用于读取、写入和操作文件数据。 https://www.w3schools.com/python/pandas/pandas_csv.asp


推荐阅读