我正在编写一个python脚本,将一个方法添加到一些iOS代码中。我需要脚本扫描文件的一个特定的行,然后开始写入文件后的一行。例如:
#实用化标记-方法
我怎么能用Python做到这一点呢?
谢谢!
柯林
发布于 2014-05-20 18:52:50
我假设您不想像您的问题所暗示的那样,实际地写出#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()https://stackoverflow.com/questions/23767431
复制相似问题