0

I have a csv file like=>

apple, 23, 45 
abricot, 45 12
grape,  123 985
apple, 18, 450

I would like to get row thanks to identifier, for instance get from apple row.. here's my code:

import csv
import re
exampleFile=open('test-csvred.csv')
exampleReader = csv.reader(exampleFile)
for row in exampleReader:
    a=str(row)
    print ('Row #' + str(exampleReader.line_num)+' ' +a)
    t=re.match("apple(.*)",a).group(1)

the code gives me=> NoneType' object has no attribute 'group' I don't really know what is my mistake... thanks in advance

4
  • why are you using the csv lib if you want a string? Post what the actual content looks like and what you expect as output Commented Dec 13, 2015 at 19:12
  • re.match only searches for a match at the beginning of the string. Try re.search. Commented Dec 13, 2015 at 19:14
  • re.search gives me the same error message. Commented Dec 13, 2015 at 19:17
  • I use csv because I need those docs to edit contents. I would like to extract the int of the third cell each time line begins by apple Commented Dec 13, 2015 at 19:18

1 Answer 1

1

Your code is basically doing what str.startswith can do:

with open("in.txt") as f:
    for line in f:
        if line.startswith("apple"):
            print(line)

Your code is obviously going to fail unless every single line startswith "apple" as match or search will return None when there is no match. Your csv file also seems to be a mess, there are different amounts of whitespace and missing commas so it is not suitable to be parsed by the csv lib.

If you want the line numbers too, use enumerate:

with open("in.txt") as f:
    for ind, line in enumerate(f, 1):
        if line.startswith("apple"):
            print(line)
Sign up to request clarification or add additional context in comments.

3 Comments

@user2216280, no worries, this basically does what your own code wa attempting to do. The csv lib is not really suitable for the sample input you provided if you need to split the data you can str.split and str.rstrip
for ind, line in enumerate(f, 1): doesn't seem to gives the line number where the startswith function is true...
Yes, just add ind to the print, print(ind, line)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.