Skip to content Skip to sidebar Skip to footer

Get To Specific Line In File, Then Start Writing After That Line

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 exa

Solution 1:

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 positionpos = 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:

withopen("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()

Post a Comment for "Get To Specific Line In File, Then Start Writing After That Line"