鱼C论坛

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

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

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

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

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

x
  1. def czjtwz(mulu,guanjianzi):
  2.     def xunzhao(zifu,fanwei):
  3.         if zifu in eachline[fanwei:]:
  4.             f = eachline.find(zifu,fanwei)
  5.             fanwei = len(zifu)+f
  6.             list1.append(f)
  7.             return xunzhao(zifu,fanwei)
  8.         else :
  9.             return list1

  10.     import os
  11.     counth = 0
  12.     list1 = []
  13.     os.chdir(mulu)
  14.     allfile = os.listdir(os.curdir)
  15.     for eachfile in allfile:
  16.         if os.path.isfile(eachfile):
  17.             if os.path.splitext(eachfile)[1]=='.txt':
  18.                 gzml = os.getcwd()
  19.                 filename = open(gzml+os.sep+eachfile)
  20.                 list2=list(filename)
  21.                 str2 = str(list2)
  22.                 filename.close()
  23.                 filename = open(gzml+os.sep+eachfile)
  24.                
  25.                 if guanjianzi in str2:
  26.                     print('在文件【%s】中找到关键字【%s】'%(gzml+os.sep+eachfile,guanjianzi))
  27.                     while counth<len(list2):
  28.                         eachline = filename.readline()
  29.                         counth+=1
  30.                         if guanjianzi in eachline:
  31.                             xunzhao(guanjianzi,0)
  32.                             print('关键字出现在第%d行,第%s个位置'% (counth,list1))
  33.                             list1 = []
  34.                     print('==========================================')
  35.         if os.path.isdir(eachfile):
  36.             czjtwz(eachfile,guanjianzi)
  37.             os.chdir(os.pardir)
  38.             
复制代码

这个代码只能访问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盘搜索)
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-7-2 04:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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