python file manipulation
Question: I have a directory /tmp/dir with two types of file names

> /tmp/dir/abc-something-server.log
>
> /tmp/dir/xyz-something-server.log
>
> ..
>
> ..

and

> /tmp/dir/something-client.log

I need append a few lines (these lines are constant) to files end with
"client.log"

> line 1
>
> line 2
>
> line 3
>
> line 4

append these four lines to files end with "client.log"

Yes I found open () "a" option will provide the desired result. but how to
select the correct file that is, exclude server.log and choose client.log ?

and For files end with "server.log"

I needed to append after a keyword say "After-this". "server.log " file has
multiple entries of "After-this" I need to find the first entry of "After-
this" and append above said four lines keep the remaining file as it is.

Any help will be great appreciated :) Thanks in advance.


Answer: not tested

    
    
    import os,glob,fileinput
    root="/tmp"
    path=os.path.join(root,"dir")
    alines=["line 1\n","line 2\n","line 3\n","line 4\n"]
    os.chdir(path)
    # for clients
    for clientfile in glob.glob("*.client.log"):
        data=open(clientfile).readlines()
        data.append(alines)
        open("temp","w").write(''.join(data))
        os.rename("temp",clientfile)
    for svrfile in glob.glob("*.server.log"):
        f=0
        for line in fileinput.FileInput(svrfile,inplace=1):
             ind=line.find("After-this")
             if ind!=-1 and not f:
                 line=line[:ind+10] + ''.join(alines) + line[ind+10:]
                 f=1
             print line
    

