简体   繁体   中英

python replace fileinput with seek

I have got a file which terminates with </END> there are chances the file may contains blank lines after </END> . I do not care about blank lines. But the last non blank word is </END> . I need to append a couple of lines before the </END> . I have done this with fileinput

for each_line in fileinput.input("testme",inplace=True):
    if each_line.strip() == '</END>':
        print "\nAdding ^.*"+source_resource+".*$ \\"
        print destination+" [R="+http_code+",L]"
    print each_line,

Can some experts please advise how can this be achieved with seek . I believe seek is very handy for cursor positing.

You have 2 possible approaches, one using an in-place write and the other implies creating a copy of the file.

The second approach is very easy to implement:

with open(src_path, "r") as in_f, open(dest_path, "w") as out_f:
    for line in in_f:
        if line == "</END>":
            out_f.write("whatever you want")
        out_f.write(line)
        out_f.write('\n')

For the first approach, we need to detect the end line and move back to its beginning:

last = 0
with open(src_path, "r+") as f:
    for line in f:
        if line == "</END>":
            f.seek(last)
            f.write("whatever you want"
            f.write(line) # rewrite the line
            f.write('\n')
        last = f.tell() # This will give us the end of the last line

I did write this code by head so there might be some errors, but you got the idea.

I wouldn't do it with seek , since there you have to specify all the offsets yourself - it forces you to explicitly split lines and the like (depending on the OS ...) - all things that tend to be error-prone.

If your grammar prescribes that each -tag is in a separate line, you can use the code you have (it's simple, understandable and presumably fast).

If you need a less strict syntax, then I would build an easy parser with pyparsing (assuming that performance is not the main concern).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM