2

So I am trying to export each line of a particular column in my csv file in a txt file; I have more than 100 lines.


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)

error :

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

I am having difficulties to figure out why it throws KeyError.

file looks like this

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

kely789456123
  • 605
  • 1
  • 6
  • 21

1 Answers1

3

You have ; as a delimiter in your csv, you need to specify that when you create an instance of csv.DictReader

reader = csv.DictReader(csvfile, delimiter=';')
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40