'How to edit the contents of .hpp file using Python file functions?

I have an HPP file that I want to edit. I want to replace some text in it. What I did is I opened the file, stored its contents in variable, replaced what I wanted to, emptied the file, and then re-wrote the string in my variable to the file.

But I have noticed that after emptying the file, there comes some weird "����" at the top. This happens when I edit any file other than a .txt file. What can I do to resolve this?

Here's my code:

file=open("my_lib.hpp", "r+")
data=file.read()
data.replace("void","int")
file.truncate(0)
file.write(data)
file.close()

Now here is the file:

�������������������������������������
�������������������������������������
�������������������������������������
�������������������������������������

//and then the rest of the code 
//( the replacement worked fine)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source