|

楼主 |
发表于 2021-5-12 18:38:28
|
显示全部楼层
- import os
- def find_fun(path, word):
- for each in os.listdir(path):
- each_path = os.path.join(path, each)
- if os.path.isfile(each_path):
- each_list = os.path.splitext(each)
- if str(each_list[1]) == '.txt':
- file = open (each_path)
- if word in file.read():
- file.close()
- print('=================================================')
- print(f'在文件【{each_path}】中找到关键字【{word}】')
- fun(each_path, word)
- else:
- next_path = each_path
- find_fun(next_path, word)
- def fun(each_path, word):
- i = 0
- count = []
- file = open (each_path)
- file_list = list(file)
- for each_line in file_list:
- i += 1
- index = each_line.find(word)
- if index != -1:
- count.append(index)
- for m in range(count[-1], len(each_line)):
- if index != -1:
- index = each_line.find(word, (count[-1] + 1), len(each_line))
- print(f'关键字出现在第 {i} 行,第{count}位置')
- count.clear()
- file.close()
- word = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
- path = os.getcwd()
- print (f'请问是否需要打印关键字【{word}】在文件中的具体位置(YES\\NO):', end = '')
- judge = input()
- if judge == 'YES' or judge == 'yes':
- find_fun(path, word)
-
复制代码
已解决了,试过gbk 和 utf8 编码方式打开,都会报错
后来在群小伙伴的提示下发现我的目标文件有点是gbk编码 有的是utf8编码
这样就导致无论用哪种方式打开总会报编码错误的BUG
最后把所有文件全部修改为gbk编码方式就可以完美运行了
如果大家发现还有BUG请在后面跟帖讨论 |
|