英文:
Why do I get a KeyError if I try to print certain columns of a CSV file given their indices?
问题
尝试在Python中解析CSV文件。以下是我目前的代码:
```python
import csv
import os
csv_file_path = r'C:\Users\ctumbs\OneDrive\General - Vision Dataset\numbers.csv'
with open(csv_file_path) as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
print(row[0], row[2], row[4], row[6])
目前我收到一个错误,错误信息为'KeyError: 0'。
当我替换行索引并仅将最后一行更改为print(row)
时,我能够生成输出,但列数太多了。以下是我的输出示例:
39431 568404 5849392
34783 383392 4933983
02941 848292 3820201
38493 283293 3929300
<details>
<summary>英文:</summary>
I'm trying to parse a CSV file in Python. This is what I have so far.
import csv
import os
csv_file_path = r'C:\Users\ctumbs\OneDrive\General - Vision Dataset\numbers.csv'
with open(csv_file_path) as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
print(row[0], row[2], row[4], row[6])
Right now I get an error that says 'KeyError: 0'.
When I replace the row indices and just have my last line as `print(row)`, I'm able to generate output, but there are too many columns. Here's an example of my output:
```none
39431 568404 5849392
34783 383392 4933983
02941 848292 3820201
38493 283293 3929300
答案1
得分: 1
csv.DictReader
每行返回一个字典,其中列标题用作键。
"KeyError: 0" 表示没有名为 "0" 的列。
如果您想根据索引选择列而不是标题,请改用 csv.reader
,它每行返回一个列表。
英文:
csv.DictReader
returns one dictionary for each row, where the column headers are used as keys.
"KeyError: 0" means that there is no column which is named "0".
If you want to select columns by their index instead of the header, use a csv.reader
instead, which returns one list for each row.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论