如何使用 Python 文件函数编辑 .hpp 文件的内容?
How to edit the contents of .hpp file using Python file functions?
我有一个要编辑的 HPP 文件。我想替换其中的一些文本。我所做的是打开文件,将其内容存储在变量中,替换我想要的内容,清空文件,然后将变量中的字符串重新写入文件。
但是我注意到清空文件后,顶部出现了一些奇怪的“����”。当我编辑 .txt 文件以外的任何文件时,就会发生这种情况。我该怎么做才能解决这个问题?
这是我的代码:
file=open("my_lib.hpp", "r+")
data=file.read()
data.replace("void","int")
file.truncate(0)
file.write(data)
file.close()
现在是文件:
�������������������������������������
�������������������������������������
�������������������������������������
�������������������������������������
//and then the rest of the code
//( the replacement worked fine)
Truncate 不会改变光标位置,只有seek 会。因此,即使文件长度为 0,您也在位置(无论原始文件长度是多少)写入。试试这个:
file=open("my_lib.hpp", "r+")
data=file.read()
data = data.replace("void","int") # replace returns a copy, doesn't operate in place
file.seek(0)
file.truncate()
file.write(data)
file.close()
我有一个要编辑的 HPP 文件。我想替换其中的一些文本。我所做的是打开文件,将其内容存储在变量中,替换我想要的内容,清空文件,然后将变量中的字符串重新写入文件。
但是我注意到清空文件后,顶部出现了一些奇怪的“����”。当我编辑 .txt 文件以外的任何文件时,就会发生这种情况。我该怎么做才能解决这个问题?
这是我的代码:
file=open("my_lib.hpp", "r+")
data=file.read()
data.replace("void","int")
file.truncate(0)
file.write(data)
file.close()
现在是文件:
�������������������������������������
�������������������������������������
�������������������������������������
�������������������������������������
//and then the rest of the code
//( the replacement worked fine)
Truncate 不会改变光标位置,只有seek 会。因此,即使文件长度为 0,您也在位置(无论原始文件长度是多少)写入。试试这个:
file=open("my_lib.hpp", "r+")
data=file.read()
data = data.replace("void","int") # replace returns a copy, doesn't operate in place
file.seek(0)
file.truncate()
file.write(data)
file.close()