如何从不包含特定值的文本文件中读取行?

时间:2018-03-13 15:20:29

标签: python

我想阅读filename中的所有行,但是searchparam1中的所有行,我都不希望它被阅读。这是我的代码,但我一直收到错误:

import cgi
import cgitb
cgitb.enable()

print("Content-Type: text/html\n")    # HTML is following

form = cgi.FieldStorage()
fileID = form.getvalue("filename")
searchParam1= form.getvalue("search1")
searchParam2 = form.getvalue("search2")

fileArray = []

with open(fileID, "r") as targetfile:
    fileArray = targetfile.readlines()

for line in targetfile:              
    if re.search(str(searchParam1).lower(), line.lower()) == None:
        print ("ok")


for i in range(0,len(fileArray)):
    print(fileArray[i])
    print("<br/>")

1 个答案:

答案 0 :(得分:0)

看起来这是一个缩进问题。您可以访问&#39; targetfile&#39;仅在with

with open(fileID, "r") as targetfile:
    fileArray = targetfile.readlines()

    for line in targetfile:              
        if re.search(str(searchParam1).lower(), line.lower()) == None:
            print ("ok")