在下面的代碼中,程序從用戶處獲取字符串數據,並將其轉換爲ascii和十六進制,並搜索某個目錄中的所有.log和.txt文件,查找純文本字符串中的字符串hex和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!!!"
你在哪裏卡住? –
你意識到這會導致它打印找到的每個文件的每一行,對嗎?如果那是你想要的,那麼錯在哪裏?看看代碼,它似乎是好的 – carlpett
我同意carlpett。它說你想打印文件,但是你真的想要文件名嗎?還有一些示例輸出會幫助堆。 –