1. 程式人生 > >python程式2(遞迴查詢某一個資料夾下所有的檔案是否含有某個特定的字串,並列印該檔名)

python程式2(遞迴查詢某一個資料夾下所有的檔案是否含有某個特定的字串,並列印該檔名)

#coding:utf-8
#author:yanjing
#date:2016/12/16
#遞迴查詢某一個資料夾下所有的檔案是否含有某個特定的字串
import os
import re
import string
#此函式的作用為遞迴查詢資料夾下所有的檔案
def dirlist(mainpath, allfilelist):
filelist = os.listdir(mainpath)
   for filename in filelist:
filepath = os.path.join(mainpath, filename)
      if os.path.isdir(filepath):
dirlist(filepath, allfilelist) else: allfilelist.append(filepath) return allfilelist #此函式的作用為在某個檔案中匹配特定字串 def findstr(filename,keyword): global everyline right=[] fp=open ( filename, 'r' ) for everyline in fp: if re.search(keyword,everyline,re.I): right.append(filename) break
return right if __name__ == "__main__": keyword='MriF43LGGq' allfile=dirlist("C:\Users\yanjing\Desktop\mypy", []) for i in range(len(allfile)): if findstr(allfile[i],keyword): print allfile[i]