Python judges whether a certain string exists in a txt file

To determine whether a certain string exists in a txt file, you can use Python's file reading function and combine it with the string search method.

The following is a simple sample code that demonstrates how to determine whether a certain string exists in a txt file:

```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}'.")
```

In the above code, the `is_string_in_file` function accepts the filename and the string to look for as parameters. The function opens the file by using the `with open` statement, and then finds the string line by line. Return `True` if a matching string is found, `False` otherwise. If the file does not exist, `FileNotFoundError` is caught and an error message is printed.

In the test example, we set the filename to 'example.txt' and the string to look for to 'hello'. If the string is found in the file, print the found message, otherwise print the not found message.

Make sure to replace 'example.txt' with the actual filename you're looking for and 'hello' with the actual string you're looking for.

Guess you like

Origin blog.csdn.net/qq_26429153/article/details/131855070