【发布时间】:2011-06-21 12:06:29
【问题描述】:
在下面的代码中,程序从用户那里获取字符串数据并将其转换为 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!!!"
【问题讨论】:
-
您确实意识到这将导致它打印找到的每个文件的每一行,对吧?如果那是你想要的,那有什么问题?看代码好像没问题
-
我同意卡佩特的观点。它说你想打印文件,但你真的想要文件名吗?还有一些示例输出将有助于堆。
标签: python regex text-formatting