|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- def czjtwz(mulu,guanjianzi):
- def xunzhao(zifu,fanwei):
- if zifu in eachline[fanwei:]:
- f = eachline.find(zifu,fanwei)
- fanwei = len(zifu)+f
- list1.append(f)
- return xunzhao(zifu,fanwei)
- else :
- return list1
- import os
- counth = 0
- list1 = []
- os.chdir(mulu)
- allfile = os.listdir(os.curdir)
- for eachfile in allfile:
- if os.path.isfile(eachfile):
- if os.path.splitext(eachfile)[1]=='.txt':
- gzml = os.getcwd()
- filename = open(gzml+os.sep+eachfile)
- list2=list(filename)
- str2 = str(list2)
- filename.close()
- filename = open(gzml+os.sep+eachfile)
-
- if guanjianzi in str2:
- print('在文件【%s】中找到关键字【%s】'%(gzml+os.sep+eachfile,guanjianzi))
- while counth<len(list2):
- eachline = filename.readline()
- counth+=1
- if guanjianzi in eachline:
- xunzhao(guanjianzi,0)
- print('关键字出现在第%d行,第%s个位置'% (counth,list1))
- list1 = []
- print('==========================================')
- if os.path.isdir(eachfile):
- czjtwz(eachfile,guanjianzi)
- os.chdir(os.pardir)
-
复制代码
这个代码只能访问txt格式的吗,我把
if os.path.splitext(eachfile)[1]=='.txt'
改为if os.path.splitext(eachfile)[1]=='.py'应该也能访问py格式才对啊,可是出错了,
对应的filename = open(gzml+os.sep+eachfile)我也改成了filename = open('%s.py'% gzml+os.sep+eachfile)也还是报错,但似乎它能找到文件才报错,为嘛啊
(顺便问下这个代码的搜索范围只能从文件夹开始,我想从盘开始要咋弄,如在整个E盘搜索) |
|