解决方法如下:
import os
def check_string_in_file(file_path, target_string):
if not os.path.exists(file_path):
print("File does not exist.")
return
with open(file_path, 'r') as file:
for line in file:
if target_string in line:
return True
return False
# 示例用法
file_path = "path/to/your/file.txt"
target_string = "example_string"
if check_string_in_file(file_path, target_string):
print("Target string found in the file.")
else:
print("Target string not found in the file.")
这个示例代码定义了一个名为check_string_in_file
的函数,它接受一个文件路径和一个目标字符串作为参数。函数首先检查文件是否存在,如果文件不存在,则打印错误消息并返回。然后,它打开文件并逐行遍历文件内容。如果目标字符串在文件中的任何一行中找到,则返回True。如果遍历完文件后仍未找到目标字符串,则返回False。
你可以根据自己的需要修改文件路径和目标字符串来检查文件中的特定字符串。使用示例中的check_string_in_file
函数,你可以轻松地在文件中检查任何字符串。