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

2024-04-26

在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 False

file_path = 'file.txt'
search_string = 'example'

search_string_in_file(file_path, search_string)

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

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