#!/usr/bin/python
# replace.py
import sys
# Replace string in a file (in place)
match=b'\t\t\r\n'
replace=b'\r\n'
filename='MyTestFile.txt'
print ("Replacing strings in",filename)
with open(filename,"rb") as f:
data = f.read().replace(match,replace)
with open(filename,"wb") as f:
f.write(data)
The trick is to open the file as a binary file, specify binary match and replace strings and write te file back as a binary file: works like a charm.