""" 此方法未测试。 代码定位 查找指定目录下的指定类型文件中是否包含指定关键字, 如果包含,则打印文件指定关键所在位置, 即第几行第几个字符。 如果遇到文件夹,则进入文件夹继续搜索。 """ """ 在文件中搜索指定关键字。 @param file 要搜索的文件路径。 @param keyword 要搜索的关键字。 @return 包含关键字出现位置的列表,每个位置由行号和字符位置组成。 """ def search_in_file(file, keyword): result = [] with open(file) as f: row_count = 0 for line in f: row_count += 1 pos = line.find(keyword) if pos != -1: result.append({ "row": row_count, "pos": pos }) return result """ 开始搜索操作。 @param begin 搜索的起始目录。 @param keyword 要搜索的关键字。 @param file_type 要搜索的文件类型。 """ def run(begin, keyword, file_type): result = {} # 查找指定目录下指定类型的文件 match = search_in_file(begin, [file_type]) for file in match: value = search_in_file(file, keyword) if value: result[file] = value # 按照文件名排序,并打印搜索结果 for key in sorted(result): print(f'在{key}中找到关键字{keyword},位置如下:') for item in result[key]: print(f'第{item["row"]}行,第{item["pos"]}个字符') if __name__ == '__main__': run("..", "python", ".py")
代码定位:查找指定目录下的指定类型文件中是否包含指定关键字
未经允许不得转载:创想未来 » 代码定位:查找指定目录下的指定类型文件中是否包含指定关键字
评论前必须登录!
注册