Monday, August 29, 2022

[FIXED] How to get values from csv files and iterate through column

Issue

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


Solution

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

# I’m using StringIO to avoid writing a file,
# if the data is in a file keep using with open(…) as f
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 = [
        int(v) for row in reader for v in row["Date"].split(",")
        ]

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


Answered By - ljmc
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.