I have a function which iterates over a text file, matches words to keys in a dictionary, and changes these words to the keys values:
def replace_operators(text):
operators = {'order': '"order"'}
f = open(text, 'r').read()
for k, v in operators.items():
cleaned = re.sub(r"\b%s\b" % k, v, f)
f = open(text, 'w')
f.truncate(0)
f.close()
text_file = open(text, 'w')
text_file.write(cleaned)
text_file.close()
This works fine, however when I add another key to the dictionary, I receive:
TypeError: expected string or bytes-like object
I've tried the solution of replacing f with str(f) in the cleaned line (suggested by this answer), however this only writes the following line to my outfile:
<_io.TextIOWrapper "name"='path/of/outfile' mode='w' encoding='cp1252'>
Does anyone know how I can add more keys without getting this kind of error?