Scarlett stone
Scarlett stone

Reputation: 225

Python cannot find the string in csv file

I was try to learn how to find a string or value in csv using python. i was think it's simple but when i was try to execute my code, i don't understand why my code cannot find the string what i want. This is my code :

import csv

with open('sample2.csv', 'rt') as baca:
    read = csv.reader(baca, delimiter='\'')
    for row in read:
        match = row[0]
        if match == "Sample":
            print match

And also i was try to print "row[0]" and the result is like this :

id      name         number
1       Sample    0123450000007 

Print a "row" without index :

{'id\tname\tnumber': '1\tSample\t0123450000007'}

The screenshot :

enter image description here

Upvotes: 1

Views: 352

Answers (2)

Amit
Amit

Reputation: 20456

It looks like demilter should be a tab

In [9]: import csv
   ...:
   ...: with open('sample2.csv', 'rt') as baca:
   ...:     read = csv.reader(baca, delimiter='\t')
   ...:     for row in read:
   ...:         match = row[1]
   ...:         if match == "Sample":
   ...:             print match
Sample

Upvotes: 2

Cory Madden
Cory Madden

Reputation: 5193

You could also use csv.DictReader which makes it easier to select the item you want. Assuming your CSV looks like this:

id,name,number
1,Sample,234234
2,NotAMatch,567657

You can print the matching rows like this:

In [159]: import csv
In [160]: with open('samples.csv') as f:
     ...:     reader = csv.DictReader(f, delimiter='\t')
     ...:     for row in reader:
     ...:         if row['name'] == "Sample":
     ...:             print(row)
     ...:             
OrderedDict([('id', '1'), ('name', 'Sample'), ('number', '234234')])

Or a little shorter with a list comprehension:

In [163]: with open('samples.csv') as f:
     ...:     reader = csv.DictReader(f)
     ...:     print([row for row in reader if row['name'] == "Sample"])

Upvotes: 1

Related Questions