本帖最后由 jackz007 于 2020-3-15 11:55 编辑 import os
f = True
while f:
opath = input('请输入待查找的初始目录:') . strip()
if opath :
if os . path . exists(opath) and os . path . isdir(opath) : break
else : print('初始目录【%s】不存在!\n' % opath)
else:
f = False
break
if f:
keywords = input('请输入要查找的关键字:')
if keywords:
yn = input ('请问是否需要打印关键字【{0}】在文件中的具体位置(YES/NO):'.format(keywords)) . strip() . lower()
if not yn : yn = 'yes'
for path , dirs , files in os . walk(opath):
for file in files:
if os . path . splitext(file)[1] . lower() in ['.txt' , '.py' , '.c' , '.cpp']:
x = os . path . join(path , file)
f = open(x , 'rt')
c , count = 0 , 0
for each in f:
d = 0
while True:
d = each . find(keywords , d)
if d >= 0:
if not count : print(x)
if yn == 'yes' : print('\t第【%d】行,第【%d】列找到关键字【%s】' % (c + 1 , d + 1 , keywords))
d , count = d + 1 , count + 1
else : break
c += 1
f . close()
if count : print('\t总共找到【%d】处关键字【%s】\n' % (count , keywords))
|