热搜:fiddler git ip 代理 m1
历史搜索

Python怎么查找文件中指定字符串?

游客2024-08-15 14:33:01

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

标签:Python