import os
def get_all_files(path):
"""
:param path: 文件的目录
:return:
"""
for root, dirs, files in os.walk(path):
for file in files:
file_path = os.path.join(root, file)
yield file_path
def find_word(file_path, word):
"""
:param file_path: 文件的路径
:param word: 被查找的单词
:return:
"""
try:
f = open(file_path, "r",encoding="utf-8")
for order, line in enumerate(f.readlines(), 1):
if line.find(word) != -1:
print("%d %s %s" % (order, file_path, word))
except Exception:
pass
finally:
f.close()
def run(path, word):
"""默认在当前路径下查找test"""
for file_path in get_all_files(path):
find_word(file_path, word)
if __name__ == '__main__':
run(path=os.getcwd(), word="test")
|