使用 csv.DictReader,我想搜索一个字符串,然后打印包含该字符串的行

M. *_*ert 2 python csv

我用 Python 编写了一个小脚本来帮助我处理一个大.csv文件,但我目前遇到了一些问题......

在程序的主要部分,它提示用户输入,然后调用一个引用这些选项的函数,就像这样......(只显示选项一):

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

    if response == 1:
        ID = input('Enter your ID: ')
        Response_one(ID)
Run Code Online (Sandbox Code Playgroud)

这个函数Response_one然后打开文件,我希望它在打印该行之前搜索并找到ID用户输入的变量在.csv, 中的位置。到目前为止,我有这样的事情:

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

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
Run Code Online (Sandbox Code Playgroud)

Any help would be hugely appreciated.

Inb*_*ose 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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Example

what id?: 1
{'ID': '1', 'DATA': 'a'}
Run Code Online (Sandbox Code Playgroud)