【发布时间】:2014-05-20 18:35:27
【问题描述】:
我正在编写一个 python 脚本来为一些 iOS 代码添加一个方法。我需要脚本来扫描文件中的特定行,然后在该行之后开始写入文件。例如:
- 脚本遇到这一行
#pragma mark - 方法
- 然后在这一行之后写方法
如何在 Python 中做到这一点?
谢谢!
科林
【问题讨论】:
-
请提及到目前为止必须尝试的内容?
我正在编写一个 python 脚本来为一些 iOS 代码添加一个方法。我需要脚本来扫描文件中的特定行,然后在该行之后开始写入文件。例如:
#pragma mark - 方法
如何在 Python 中做到这一点?
谢谢!
科林
【问题讨论】:
正如您的问题所暗示的,我假设您实际上不想覆盖 #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()
【讨论】: