Python怎么查找文件中指定字符串?
在 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怎么查找文件中指定字符串?
码云笔记 » Python怎么查找文件中指定字符串?