此代码从html获取数据并在afile中搜索。如果找到搜索,则在Web浏览器上进行打印。现在我查询为什么在b.append()行之后写入found = False。 b'coz如果我们不写它会在网络浏览器上打印文件中的所有数据
#!/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()
答案 0 :(得分:2)
只需在每次循环传递结束时将found
变量更新为False
即可。这样做是因为新迭代应该以{{1}}开头(默认情况下在每次搜索开始时)。否则,一旦found = False
将line
设置为found
,它将始终保持True
(对于以下True
s,这是错误的。)
实际上,从我的观点来看,最好将这些变量放在循环的开头,作为一种初始化部分。 (但这是一个品味和'良好实践'的问题,在人们之间存在显着差异)