I'm trying to replace a single character '°' with '?' in an edf file with binary encoding.(File) I need to change all occurances of it in the first line.
I cannot open it without specifying read binary. (The following fails with UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 3008: invalid start byte)
with open('heartbeat-baseline-700001.edf') as fin:
lines = fin.readlines()
I ended up trying to replace it via this code
with open("heartbeat-baseline-700001.edf", "rb") as text_file:
lines = text_file.readlines()
lines[1] = lines[1].replace(str.encode('°'), str.encode('?'))
for i,line in enumerate(lines):
with open('heartbeat-baseline-700001_python.edf', 'wb') as fout:
fout.write(line)
What I end up with is a file that is exponentially smaller (7KB vs 79MB) and does not work.
What seems to be the issue with this code? Is there a simpler way to replace the character?
forloop, you are just overwriting a single line to the file, not (i assume) appending. Tryabinstead ofwb? Or exchangeforandwith openso that thefout.writeis done while the file is openforloop inside the secondwithstatement, not the other way around