在下面的代码中,程序从用户那里获取字符串数据并将其转换为 ascii 和 hex,并在某个目录中的所有 .log 和 .txt 文件中搜索纯字符串、十六进制和 ascii 值的字符串。程序打印 # 行、找到的字符串类型以及找到字符串的文件路径。但是,如果找到字符串,我不仅希望它打印文件,我还希望它打印在搜索但未找到的文件中搜索的文件和路径和字符串。我是新手,所以请不要对问题的简单性感到沮丧。我还在学习。谢谢。下面的代码:
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 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!!!"