python - 如何在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)
解决方案
尝试使用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
推荐阅读
- c# - Blazor 中的 EditForm 有两个 InputSelects,提交按钮似乎不会触发
- navigation - 路线模拟期间停止调用`onNewInstructionEvent`(HERE Premium SDK)
- zend-framework3 - Zf3 使用数据库中的数据填充选择元素
- themes - Is it possible to replace Keycloak's build in account-console?
- google-sheets - 带有 if 条件的 Arrayformula - 仅隐藏行值而不包括它们
- python - 在哪里使用 Django 框架最好地执行数据库操作?
- ios - 如何在 Swift 中等待异步函数?
- conv-neural-network - 如何修复错误“无法分配给非变量...”?
- docker - nginx反向代理到其他nginx 502坏网关
- python - 何时判断我们的 CNN 模型是否过拟合?