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 Replacing words in text file using a dictionary and How to search and replace text in a file using Python?
As like:
# edit print line to print (line)
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 field in fields:
if field in line:
line = line.replace(field, fields[field])
print (line)
My file is encoding in utf-8
.
When I run this, the console shows this error:
UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>
When add: encoding = "utf8"
to fileinput.FileInput()
its show an error:
TypeError: __init__() got an unexpected keyword argument 'encoding'
When add: openhook=fileinput.hook_encoded("utf8")
to fileinput.FileInput()
it show error:
ValueError: FileInput cannot use an opening hook in inplace mode
I do not want to insert a subcode 'ignore'
ignoring errors.
I have file, dictionary and want replace values from dictionary into file like stdout
.
Source file in utf-8
:
Plain text on the line in the file.
This is a greeting to the world.
Hello world!
Here's another plain text.
And here too!
I want to replace the word world
with the word earth
.
In dictionary: {"world": "earth"}
Modified file in utf-8
:
Plain text on the line in the file.
This is a greeting to the earth.
Hello earth!
Here's another plain text.
And here too!