I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.
Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.
The code doesn't produce any errors, but also doesn't do any replacing.
import fileinput
text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}
for line in fileinput.input(text, inplace=True):
line = line.rstrip()
for i in fields:
for field in fields:
field_value = fields[field]
if field in line:
line = line.replace(field, field_value)
print line