为什么如果我尝试打印CSV文件中特定列的索引,会收到KeyError错误?

huangapple go评论57阅读模式
英文:

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&#39;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 &#39;KeyError: 0&#39;.

When I replace the row indices and just have my last line as `print(row)`, I&#39;m able to generate output, but there are too many columns. Here&#39;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.

huangapple
  • 本文由 发表于 2023年7月14日 07:46:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683896.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定