|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import os
file=[]
def search_file():
os.chdir('F:\Python练习')
for each_file in os.listdir(os.curdir):
ext=os.path.splitext(each_file)[1]
if ext=='.txt':
file.append(os.getcwd()+os.sep+each_file+os.linesep)
if os.path.isdir(each_file):
search_file()
os.chdir(os.pardir)
def search_line(keyword):
search_file()
for each_file in file:
f=open(each_file)
count=0
for each_line in f:
count+=1
if keyword in each_line:
print('在文件【%s】中找到关键字【%s】'%(each_file,keyword))
location=search_keyword(each_line,keyword)
print('关键字出现在第%d行,第%s个位置。'%(count,str(location)))
f.close()
def search_keyword(line,keyword):
location=[]
while begin!=-1:
begin=line.find(keyword)
location.append(begin+1)
begin=line.find(keyword,begin)
return location
keyword=input('请将该脚本放于待查找的文件内,请输入关键字:')
judge=input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):')
if judge in ['YES','Yes','yes']:
search_line(keyword)
else:
print('不打印算了')
会报
Traceback (most recent call last):
File "F:\Python练习\a.py", line 37, in <module>
search_line(keyword)
File "F:\Python练习\a.py", line 14, in search_line
search_file()
File "F:\Python练习\a.py", line 10, in search_file
search_file()
File "F:\Python练习\a.py", line 10, in search_file
search_file()
File "F:\Python练习\a.py", line 10, in search_file
search_file()
[Previous line repeated 986 more times]
File "F:\Python练习\a.py", line 6, in search_file
ext=os.path.splitext(each_file)[1]
File "E:\python\lib\ntpath.py", line 227, in splitext
return genericpath._splitext(p, '\\', '/', '.')
File "E:\python\lib\genericpath.py", line 127, in _splitext
sepIndex = max(sepIndex, altsepIndex)
RecursionError: maximum recursion depth exceeded in comparison
这个错误,调试了半天也不对,求大神解答
你不设置目录,岂不是永远在当前的目录里面执行? def search_file(start_dir, target):
os.chdir(start_dir)
allfile = os.listdir(os.curdir)
# print(allfile)
for each_file in allfile:
# print(each_file)
ext = os.path.splitext(each_file)[1]
if ext in target:
vedio_list.append(os.getcwd() + os.sep + each_file + os.linesep) # 使用os.sep是程序更标准
if os.path.isdir(each_file):
try:
search_file(each_file, target) # 递归调用
os.chdir(os.pardir) # 递归调用后切记返回上一层目录
except OSError as reason:
print(reason)
continue
给你个参考吧,实在不喜欢解释递归的问题。
|
|