user2563044
user2563044

Reputation:

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 example:

#pragma mark - Method

How can I do that in Python?

Thanks!

Collin

Upvotes: 0

Views: 94

Answers (1)

kindall
kindall

Reputation: 184071

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

Upvotes: 1

Related Questions