首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >进入文件中的特定行,然后在该行之后开始编写。

进入文件中的特定行,然后在该行之后开始编写。
EN

Stack Overflow用户
提问于 2014-05-20 18:35:27
回答 1查看 85关注 0票数 0

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

  • 脚本遇到这一行

#实用化标记-方法

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

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

谢谢!

柯林

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-20 18:52:50

我假设您不想像您的问题所暗示的那样,实际地写出#pragma标记后面的任何内容。

代码语言:javascript
复制
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)

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

代码语言:javascript
复制
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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23767431

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档