在单独的txt文件中显示每行csv的显示键错误

时间:2019-06-12 13:56:57

标签: python csv format reader

因此,我尝试将CS​​V文件中特定列的每一行导出到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.

enter image description here

1 个答案:

答案 0 :(得分:3)

您将// change ',' to '.' document.getElementById('only_float').addEventListener('keypress', function(e){ if (e.key === ','){ // get old value var start = e.target.selectionStart; var end = e.target.selectionEnd; var oldValue = e.target.value; // replace point and change input value var newValue = oldValue.slice(0, start) + '.' + oldValue.slice(end) e.target.value = newValue; // replace cursor e.target.selectionStart = e.target.selectionEnd = start + 1; e.preventDefault(); } })作为csv中的定界符,您需要在创建csv.DictReader的实例时指定

<input type="text" id="only_float" />