Home > Back-end >  How to get values from csv files and iterate through column
How to get values from csv files and iterate through column

Time:06-14

My csv File sample :

'Date','Category','Ability'
'21,2,5','Sparrow','Air,land'
'4,5,6','Eagle','Air,Land'

My current code:

with open(Filepath,'r') as f :
 user_read=csv.reader(f)
 dict_date=[line['Date'] for line in user_read]
print(dict_date)

Error :

TypeError : list indices must be integer or slices,not str

My expected Output :

[21,2,5,4,5,6]

Any ideas.. So my Category and Ability has seperate Dictionary

CodePudding user response:

You're accessing the rows as dicts, which is available through csv.DictReader, and also you're not setting the quotechar for the dialect you're using which therefore defaults to ".

The following does both and works in the way you want.

import csv
from io import StringIO

buf = StringIO(
    """\
'Date','Category','Ability'
'21,2,5','Sparrow','Air,land'
'4,5,6','Eagle','Air,Land'
"""
)

with buf as f:
    reader = csv.DictReader(f, quotechar="'")
    date = []
    date = [
        int(v) for row in reader for v in row["Date"].split(",")
        ]

print(date)  # [21, 2, 5, 4, 5, 6]

CodePudding user response:

Try:

import csv


all_data = []
with open("data.csv", "r") as f_in:
    reader = csv.reader(f_in, quotechar="'")

    next(reader)  # skip header

    for row in reader:
        all_data.extend(map(int, row[0].split(",")))

print(all_data)

Prints:

[21, 2, 5, 4, 5, 6]
  • Related