python如何查找文件中指定字符串

   2024-10-25 3690
核心提示:在Python中可以使用以下代码来查找文件中指定的字符串:def search_string_in_file(file_path, search_string):with open(file_p

在Python中可以使用以下代码来查找文件中指定的字符串:

def search_string_in_file(file_path, search_string):    with open(file_path, 'r') as file:        for line in file:            if search_string in line:                print(f'Found "{search_string}" in the file.')                return True    print(f'"{search_string}" not found in the file.')    return Falsefile_path = 'file.txt'search_string = 'example'search_string_in_file(file_path, search_string)

在上面的代码中,search_string_in_file函数接收文件路径和要查找的字符串作为参数。它打开文件并逐行读取文件内容,检查每行是否包含指定的字符串。如果找到了字符串,它将打印消息并返回True。如果未找到字符串,它将打印相应消息并返回False。

您可以将文件路径和要查找的字符串替换为您要查找的实际文件路径和字符串。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号