M. Herbert
M. Herbert

Reputation: 41

using csv.DictReader, I want to search for a string and then print the row containing that string

I have written a small script in Python to help me work with a large .csv file, but I'm currently having a few issues...

In the main of the program it prompts the user for an input, then calls a function referring to those options, like so... (only showing option one):

def Main():
    response = input('1, 2 or 3? ')

    if response == 1:
        ID = input('Enter your ID: ')
        Response_one(ID)

This function Response_one then opens the file, and I want it to search through and find where the ID variable that the user entered is present in the .csv, before printing that line. So far I have something like this:

def Response_one(ID):
    file_csv = csv.DictReader(open('my_file.csv'))
    for row in file_csv:
        if row['ID'] == ID:
            print row

I got to this point by following a few things online but I'm now stuck. I've been testing with IDs that I know exist within the table such as 'ENSG00000210049', but I get the error message:

NameError: name 'ENSG00000210049' is not defined

Any help would be hugely appreciated.

Upvotes: 2

Views: 2124

Answers (1)

Inbar Rose
Inbar Rose

Reputation: 43447

Your main problem is that input function. You are getting the error because of this:

input function in Python 2.7, evaluates whatever your enter, as a Python expression. If you simply want to read strings, then use raw_input function in Python 2.7, which will not evaluate the read strings.

If you are using Python 3.x, raw_input has been renamed to input. Quoting the Python 3.0 release notes


But lets give you a nice example to sort you out.

data.csv

ID,DATA
1,a
2,b
3,c

Sample Code for Python 2

id = raw_input('what id?: ')
with open('data.csv', 'rb') as f:
    for row in csv.DictReader(f):
        if row['ID'] == id:
            print row

Sample Code for Python 3

id = input('what id?: ')
with open('data.csv', 'rb') as f:
    for row in csv.DictReader(f):
        if row['ID'] == id:
            print row

Example

what id?: 1
{'ID': '1', 'DATA': 'a'}

Upvotes: 5

Related Questions