以下のコードでは、プログラムはユーザーから文字列データを取得し、ASCII および 16 進数に変換し、特定のディレクトリ内のすべての .log および .txt ファイルをプレーン文字列、16 進数、および 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!!!"