利用遞歸遍歷指定目錄及其子目錄,比對文件名是否包含關鍵字:
#search.py
import os
import sys
def search(path, word):
for filename in os.listdir(path):
fp = os.path.join(path, filename)
if os.path.isfile(fp) and word in filename:
print fp
elif os.path.isdir(fp):
search(fp, word)
search(sys.argv[1], sys.argv[2])
使用方式:
python search.py directory_path keyword
同樣遞歸遍歷,但改為逐行讀取文件內容進行比對,命中一處即印出並跳出:
#search.py
import os
import sys
def search(path, word):
for filename in os.listdir(path):
fp = os.path.join(path, filename)
if os.path.isfile(fp):
with open(fp) as f:
for line in f:
if word in line:
print fp
break
elif os.path.isdir(fp):
search(fp, word)
search(sys.argv[1], sys.argv[2])
使用方式:
python search.py directory_path keyword