python 判断txt文件中是否存在某字符串

要判断一个txt文件中是否存在某个字符串,可以使用Python的文件读取功能,并结合字符串查找方法来实现。

下面是一个简单的示例代码,演示了如何判断一个txt文件中是否存在某个字符串:

```python
def is_string_in_file(filename, search_string):
    try:
        with open(filename, 'r') as file:
            for line in file:
                if search_string in line:
                    return True
    except FileNotFoundError:
        print(f"File '{filename}' not found.")
    return False

# 测试示例
filename = 'example.txt'
search_string = 'hello'

if is_string_in_file(filename, search_string):
    print(f"String '{search_string}' is found in file '{filename}'.")
else:
    print(f"String '{search_string}' is not found in file '{filename}'.")
```

在以上代码中,`is_string_in_file`函数接受文件名和要查找的字符串作为参数。函数通过使用`with open`语句打开文件,然后逐行查找字符串。如果找到了匹配的字符串,就返回`True`,否则返回`False`。如果文件不存在,会捕获`FileNotFoundError`并打印错误消息。

在测试示例中,我们将文件名设置为'example.txt',要查找的字符串设置为'hello'。如果在文件中找到了字符串,就打印找到的消息,否则打印未找到的消息。

请确保将'example.txt'替换为要查询的实际文件名,将'hello'替换为要查找的实际字符串。

猜你喜欢

转载自blog.csdn.net/qq_26429153/article/details/131855070
今日推荐