鱼C论坛

 找回密码
 立即注册
查看: 894|回复: 1

查找关键字在文件夹中的的具体位置(在什么文件以及这个文件的文件的什么位置)

[复制链接]
发表于 2020-3-9 15:43:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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盘搜索)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-3-9 15:45:02 | 显示全部楼层
小甲鱼30课 的课后第四题题,就像扩展下能不能访问py格式的内容,它作业是txt的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-9 15:50

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表