2

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.

M. Herbert
  • 41
  • 7
  • Can you post some sample data for the CSV? – Mani Apr 14 '16 at 11:56
  • Are you using Python 2.x or 3.x? `input()` is different in these versions. – Inbar Rose Apr 14 '16 at 11:56
  • Hey, I'm using Python 2.x and my table looks a little like; ID , Gene , Protein 1 , x1 , x2 2 , x3 , x4 My apologies for the awful table, it would seem that stackoverflow doesn't support tables.. – M. Herbert Apr 14 '16 at 12:02

1 Answers1

5

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'}
Community
  • 1
  • 1
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131