To check if a word exists in the file, separated by a space:
with open(filename) as file: found = (word in file.read().split())
Or the same thing, but reading line by line, rather than loading everyone in memory:
with open(filename) as file: found = any(word in line.split() for line in file)
If the file format is one word (/ user) per line:
with open(filename) as file: found = any(word == line.strip() for line in file)
You do not need regular expressions in simple cases. If there can be several words in a string, and in this case there can be arbitrary punctuation, you can use the regular expression associated with it:
import re matched = re.compile(r"\b" + re.escape(word) + r"\b").search with open(filename) as file: found = any(matched(line) for line in file)
\b regular expression matches the word boundary (start or end of a word). Symbols of a word are letters, numbers and the underscore. re.escape() used if the word contains regular expression metacharacters such as * .
source share