tags:

views:

87

answers:

1

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.

+3  A: 

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
ghostdog74
I'll test it and let you know the status ..thanks :)
lakshmipathi
it says type error ...how to fix this ?>open("temp","w").write(''.join(data))>TypeErrorand i think there is a typo --- is it >line=line[:ind+10] + ''.join(alist) + line[ind+10:]or >line=line[:ind+10] + ''.join(alines) + line[ind+10:]
lakshmipathi
see edit. `data=data.append(alines)` should be just `data.append(alines)`. and yes, its a typo for the other one. You can just test it out right? run it with interpreter and find out.
ghostdog74
I have changed the files as you said, i'm getting different error this time - File "file_mani.py", line 9, in <module> open("temp","w").write(''.join(data))TypeError: sequence item 64: expected string, list found
lakshmipathi
do data+=alines instead of using append, append will append alines as a single element of type list.
UncleZeiv
Yes,,adding data+=alines does the trick. Thanks UncleZeiv.Thanks for the script ,ghostdog74 !!!
lakshmipathi