您的位置:首页 > 编程语言 > Python开发

python脚本:搜索某一目录下出现特定字符串的文件

2009-12-16 22:31 1316 查看
2009年10月31日 星期六 23:55 from os.path import walk, join, normpath from os import chdir, remove import re import os import sys import getopt def find_file_by_pattern(pattern='.*', base=".", circle=True): re_file = re.compile(pattern) if base == ".": base = os.getcwd() final_file_list = [] print "You are searching " + pattern + " under folder: " + base + "..." cur_list = os.listdir(base) for item in cur_list: full_path = os.path.join(base, item) if full_path.endswith(".doc") or full_path.endswith(".bmp") or\ full_path.endswith(".wpt") or full_path.endswith(".dot"): continue #print full_path bfile = os.path.isfile(item) #print bfile if os.path.isfile(full_path): print "Searching[" + pattern + "]..." fp = open(full_path) searchitem = fp.read() #if re_file.search(full_path): if re_file.search(searchitem): final_file_list.append(full_path) print "********* Find: " + full_path else: #非文件则递归查找其下的文件 final_file_list += find_file_by_pattern(pattern, full_path) return final_file_list #if __name__ == '__main__': opts, args = getopt.getopt(sys.argv[1:], "f:p:", ["file=", "pattern="]) for o, f in opts: global myPattern global myFile if o in ("-f", "--file") : myFile=f #print "file" + myFile if o in ("-p", "--pattern") : myPattern=f #print "pattern" + myPattern result = find_file_by_pattern(myPattern, myFile) for item in result: print "Find: " + item
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐