ich habe die folgende Datei:
[codebox=text file=foo.csv]
"foo","bar","baz"
"data","additional data","some other stuff"
"line two","with a newline
in a field","and another field"
"other","\"data in quotes\" and no newline","here"
"more","\"data in quotes\" containing
n'äääewline","even more data"
[/code]
und csv.DictReader macht daraus dies:
Code: Alles auswählen
Python 3.6.2 (default, Jul 20 2017, 03:52:27)
IPython 5.3.0 -- An enhanced Interactive Python.
In [1]: import csv
In [2]: infile = open('foo.csv', mode='r', newline='', encoding='utf-8')
In [3]: mycsv = csv.DictReader(infile)
In [4]: for line in mycsv:
...: print(line)
...:
OrderedDict([('foo', 'data'), ('bar', 'additional data'), ('baz', 'some other stuff')])
OrderedDict([('foo', 'line two'), ('bar', 'with a newline\nin a field'), ('baz', 'and another field')])
OrderedDict([('foo', 'other'), ('bar', '\\data in quotes\\" and no newline"'), ('baz', 'here')])
OrderedDict([('foo', 'more'), ('bar', '\\data in quotes\\" containing'), ('baz', None)])
OrderedDict([('foo', 'n\'äääewline"'), ('bar', 'even more data'), ('baz', None)])
In [5]:
Dass das einleitende Anführungszeichen am Ende '\\' statt '\"' ist, wäre zu verschmerzen, aber dass die Zeile in der CSV-Datei auf zwei Elemente des DictReaders aufgeteilt wird, lässt sich im Nachhinein nicht so einfach auffangen.
Die eigentliche Datei, mit der ich arbeiten will, ist das Resultat eines MySQL-Exports, den ich kontrolliere, ich könnte also falls nötig auch da ansetzen.
Was mache ich falsch?