【问题标题】:How to edit the contents of .hpp file using Python file functions?如何使用 Python 文件函数编辑 .hpp 文件的内容?
【发布时间】:2021-05-27 05:43:22
【问题描述】:

我有一个要编辑的 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)

【问题讨论】:

    标签: python file-io


    【解决方案1】:

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多