Home > OS >  How to get csv rows as array with Python csv?
How to get csv rows as array with Python csv?

Time:09-20

I have an csv file that looks like

a
b
c
d
e

and a code that looks like

import csv
def func():
    with open('zumatchende.csv', mode='r') as csv_datei:
        csv_datei=csv.DictReader(csv_datei, delimiter=";", dialect="excel")
        for row in csv_datei:
            print(row)



func()

i would have expected an output like

['a']
['b']
['c']
['d']
['e']

but i get

{'a':'b'}
{'a':'c'}
{'a':'d'}
{'a':'e'}

i used this often times before and i always got the row back as an array with each element of the row as one element of the array. I dont understand why this is now formated in another data type and even puts together 2 lines into one. How can i fix this? Or what am I doing wrong? The code that i used in other places which works fine looks the same, exept the file name.

CodePudding user response:

If you don't specify fieldnames when you create the DictReader, it gets the field names from the first row.

CodePudding user response:

You are trying to fetch the dictionary and printing the dictionary. Try to fetch the value instead of complete dictionary by using following code: print(list(row['a'])

CodePudding user response:

Short answer:

with open('zumatchende.csv') as f:
    cf = csv.reader(f)
    row = [e[0] for e in cf]        
    
row

Out[14]: ['a', 'b', 'c', 'd']

Long answer:

Per the docs, DictReader outputs a dictionary whose keys are given by the optional fieldnames parameter. If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames.

See a similar question here.

  • Related