PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 29, 2022

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

 August 29, 2022     csv, list, python, reader     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing