【问题标题】:Export each lines of csv in a seperated txt file display key error在单独的文本文件中导出csv的每一行显示键错误
【发布时间】:2019-10-27 01:43:29
【问题描述】:

所以我试图将 csv 文件中特定列的每一行导出到 txt 文件中;我有 100 多行。


import csv


import csv

with open('MF.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=';')
    for row in reader:
        file_name = "{}_{}.txt".format(row['id'], row['labels'])
        line = row['sentences']
        with open(file_name, 'w') as output:
            output.write(line)

错误:

Traceback (most recent call last):
  File "csv_to_txt.py", line 7, in <module>
    file_name = "{}_{}.txt".format(row['id']; row['labels'])
KeyError: 'id'

我很难弄清楚它为什么会抛出 KeyError。

文件看起来像这样

id;labels;sentences
1;M;On a presque laissé 
2;M;ça ne changera rien
3;M; [...], je voyais ça la lune.
4;M;ça existe 
5;M;Ce qui.
6;M;La facilité de changer.

【问题讨论】:

  • 请在创建DictReader时指定正确的分隔符

标签: python csv format reader


【解决方案1】:

您的 csv 中有 ; 作为分隔符,您需要在创建 csv.DictReader 的实例时指定它

reader = csv.DictReader(csvfile, delimiter=';')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-26
    • 2019-08-18
    • 2017-06-23
    • 2012-01-16
    • 2018-02-21
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多