转到文件中的特定行,然后在该行之后开始写入 [英] Get to specific line in file, then start writing after that line
本文介绍了转到文件中的特定行,然后在该行之后开始写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个python脚本,将方法添加到某些iOS代码中.我需要脚本来扫描文件中的特定行,然后在该行之后开始写入文件.例如:
I'm writing a python script to add a method to some iOS code. I need the script to scan the the file for a specific line and then start writing to the file after that line. For example:
- 脚本遇到了这一行
#pragma标记-方法
- 然后在此行之后写入方法
如何在Python中做到这一点?
How can I do that in Python?
谢谢!
柯林
推荐答案
正如您的问题所暗示的,我假设您实际上不想覆盖#pragma
标记之后的所有内容.
I'm assuming that you don't want to actually write over anything that comes after the #pragma
marker, as your question implies.
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)
如果您确实想覆盖文件中的其余文本,则更为简单:
If you do want to overwrite the rest of the text in the file, that's simpler:
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()
这篇关于转到文件中的特定行,然后在该行之后开始写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文