无法在python中搜索文件中的数据

时间:2013-10-28 12:38:32

标签: python cgi

我有一个文件abcd.txt

Shashank  Saxena 24 male
Saurabh Parikh 23 male
Pradip Pillai 32 male

我有search.py​​脚本搜索此文件。 此search.py​​从html文件中获取值并在abcd.txt文件中搜索。 HTML有4个字段,即名字,姓氏,年龄和性别。当在firstname字段中输入数据时,它将被搜索,但不会被其他字段搜索到

#!/usr/bin/python
import cgi

def get_search():


    found = False

    form = cgi.FieldStorage()
    Fname = form.getvalue('firstname')
    Lname = form.getvalue('lastname')
Age = form.getvalue('age')
Gender = form.getvalue('gender')

print "Content-type:text/html\n"

f = open("/tmp/abcd.txt","r")

for line in f:
    temp = line.split()
    #print temp
    Fsearch = temp[0]
    Lsearch = temp[1]
    Asearch = temp[2]
    Gsearch = temp[3]

    if Fname.lower() in Fsearch.lower():
        print line
        found = True

    if Lname.lower() in Lsearch.lower():
        print line
        found = True

    if Age in Asearch:
        print line
        found = True

    if Gender in Gsearch:
        print line
        found = True

if not found:
    print "No such Records"

    '''
    if Fname in temp or Lname in temp or Age in temp or Gender in temp:
        print "Hello", line
        found = True
if not found:
    print "No matched records"              
    '''

get_search()

2 个答案:

答案 0 :(得分:0)

您确定正确输入了LnameAgeGender的值吗? 剩下的对我来说很好。

答案 1 :(得分:0)

#!/usr/bin/python
import cgi

def get_search():

    found = False

    form = cgi.FieldStorage()
    Fname = form.getvalue('firstname', '')
    Lname = form.getvalue('lastname', '')
    Age = form.getvalue('age', 0)
    Gender = form.getvalue('gender', '')


    f = open("/tmp/abcd.txt","r")
    b = []
    for line in f:
        temp = line.split()

        Fsearch = temp[0]
        Lsearch = temp[1]
        Asearch = temp[2]
        Gsearch = temp[3]

        if Fname and Fname.lower() in Fsearch.lower():
            found = True

        if Lname and Lname.lower() in Lsearch.lower():
            found = True

        if Age and Age == Asearch:
            found = True

        if Gender and Gender in Gsearch:
            found = True
        if found:
            b.append(line)
        found = False
    f.close()
    print "Content-type:text/html\n"
    if len(b) == 0:
        print "No records found"
    else:
        for each in b:
             print each

get_search()