是BB啊 发表于 2021-4-23 13:06:23

每日一问

本帖最后由 是BB啊 于 2021-4-24 14:31 编辑

不知道我的代码有什么问题,运行后不报错但是不打印,有没有大佬帮忙看看

import os
def key_count():
    time = each_line.count(key)
    return time

def find_something(start_dir,key):
    all_file = os.walk(start_dir)
    for i in all_file:
      for each_file in i:
            txt = os.path.splitext(each_file)
            if txt == '.txt':
                f = open(each_file)
               
                line = 0
               
                for each_line in each_file:
                  
                  line += 1
                  
                  if key in each_line:
                        time = key_count()
                        
                        loc = []
                        location = -1
                        
                        print(format('','=^50'))
                        print('在文件【%s】中找到关键字【%s】' % (os.getcwd + os.sep + each_file,key))
                        for j in range(time):
                            location = each_line.find(key,location+1)
                            loc.append(location)
                        print('关键字出现在第 %s 行,第%s个位置' % (line,location))
                        
                f.close()

start_dir = 'D:\\python\\试着写\\saysomething1.txt'
key = input('请将脚本放于待查找的文件夹内,请输入关键词:')
find_something(start_dir,key)

帅周 发表于 2021-4-23 13:36:12

没有key

是BB啊 发表于 2021-4-23 13:49:21

帅周 发表于 2021-4-23 13:36
没有key

有的,我创了一个有key的文件
页: [1]
查看完整版本: 每日一问