到达文件中的特定行,然后在该行之后开始写入

时间:2014-05-20 18:35:28

标签: python file io

我正在编写一个python脚本来为某些iOS代码添加方法。我需要脚本扫描文件中的特定行,然后在该行之后开始写入文件。例如:

  • 脚本遇到此行

#pragma mark - 方法

  • 然后在此行之后写入方法

我怎么能用Python做到这一点?

谢谢!

科林

1 个答案:

答案 0 :(得分:1)

我假设你不想实际写下#pragma标记之后的任何内容,正如你的问题所暗示的那样。

marker = "#pragma Mark - Method\n"
method = "code to add to the file\n"

with open("C:\codefile.cpp", "r+") as codefile:
    # find the line
    line = ""
    while line != marker:
        line = codefile.readline()
    # save our position
    pos = codefile.tell()
    # read the rest of the file
    remainder = codefile.read()
    # return to the line after the #pragma
    codefile.seek(pos)
    # write the new method
    codefile.write(method)
    # write the rest of the file
    codefile.write(remainder)

如果你想覆盖文件中的其余文本,那就更简单了:

with open("C:/codefile.cpp", "r+") as codefile:
    # find the line
    line = ""
    while line != marker:
        line = codefile.readline()
    # write the new method
    codefile.write(method)
    # erase everything after it from the file
    codefile.truncate()