Python program to store every input entered into a file, and then checks if another…
- User
Python program to store every input entered into a file, and then checks if another inputted string is in that file
- Assistantpython
# Store every input in a file with open("input.txt", "a") as file: while True: user_input = input("Enter a string (or 'exit' to stop): ") if user_input.lower() == "exit": break file.write(user_input + "\n") # Check if a string is in the file search_string = input("Enter a string to search in the file: ") with open("input.txt", "r") as file: for line in file: if search_string in line: print(f"The string '{search_string}' is in the file.") break else: print(f"The string '{search_string}' is not in the file.")This program first stores every input entered by the user into a file named "input.txt". It continues to prompt the user for input until the user types "exit".
- User
This program will be true if even a single letter matches, how to prevent this?
- Assistant
If you want to check if an exact string (and not just a substring) is present in the file, you can modify the code to split each line based on whitespace and then compare the inputted string with each word in the line. Here's the updated code:
python# Store every input in a file with open("input.txt", "a") as file: while True: user_input = input("Enter a string (or 'exit' to stop): ") if user_input.lower() == "exit": break file.write(user_input + "\n") # Check if a string is in the file search_string = input("Enter a string to search in the file: ") with open("input.txt", "r") as file: for line in file: words = line.strip().split() if search_string in words: print(f"The string '{search_string}' is in the file.") break else: print(f"The string '{search_string}' is not in the file.")