【问题标题】:Get to specific line in file, then start writing after that line获取文件中的特定行,然后在该行之后开始写入
【发布时间】:2014-05-20 18:35:27
【问题描述】:

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

  • 脚本遇到这一行

#pragma mark - 方法

  • 然后在这一行之后写方法

如何在 Python 中做到这一点?

谢谢!

科林

【问题讨论】:

  • 请提及到目前为止必须尝试的内容?

标签: python file io


【解决方案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()

【讨论】:

  • 非常感谢,我实际上想出了另一种解决方案,但最好不要删除标记后面的内容。谢谢!
猜你喜欢
  • 2014-11-24
  • 2016-02-09
  • 2018-12-16
  • 2022-12-24
  • 2013-06-02
  • 2014-10-23
  • 1970-01-01
  • 1970-01-01
  • 2019-11-18
相关资源
最近更新 更多