如何在CSV文件中跳过标题行,而在python中读取


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)

尝试使用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

相关内容

最新更新