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

888
2024/3/7 16:41:57
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python常见的内置对象有哪些