elif stament應該打印在我進行的搜索中找不到的日誌文件和路徑。但是,它們產生在單個文件中搜索的每一行(大量信息)。我究竟做錯了什麼?有條件的elif語句不會產生正確的結果
for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
result = regex.search(whitespace.sub('', line))
if result:
template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())
print output
temp.write(output)
break
elif not result:
template = "\nLine: {0}\nString not found in File: {1}\nString Type: {2}\n\n"
output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())
print output
temp.write(output)
else:
print "There are no files in the directory!!!"
實際代碼:
elif searchType =='2':
print "\nDirectory to be searched: " + directory
print "\nFile result2.log will be created in: c:\Temp_log_files."
paths = "c:\\Temp_log_files\\result2.log"
temp = file(paths, "w")
userstring = raw_input("Enter a string name to search: ")
userStrHEX = userstring.encode('hex')
userStrASCII = ''.join(str(ord(char)) for char in userstring)
regex = re.compile(r"(%s|%s|%s)" % (re.escape(userstring), re.escape(userStrHEX), re.escape(userStrASCII)))
goby = raw_input("Press Enter to begin search (search ignores whitespace)!\n")
def walk_dir(directory, extensions=""):
for path, dirs, files in os.walk(directory):
for name in files:
if name.endswith(extensions):
yield os.path.join(path, name)
whitespace = re.compile(r'\s+')
for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
result = regex.search(whitespace.sub('', line))
if result:
template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())
print output
temp.write(output)
#break
elif result not in line:
output = fileinput.filename()
print output
temp.write(output)
break
else:
print "There are no files in the directory!!!"
你爲什麼使用'elif'?一個簡單的'else'就足夠了。 –
在'elif'塊中(即如果'result'是False-ish),調用'result.group()'應該引發一個異常。 – unutbu
所以它永遠不會進入'elif'部分?你能顯示你使用的正則表達式和一個文件內容的樣本嗎? @unutbu:是的,但它似乎並沒有去那裏。 – phant0m