Python file handling
I have a directory / tmp / dir with two types of filenames
/tmp/dir/abc-something-server.log
/tmp/dir/xyz-something-server.log
..
..
and
/tmp/dir/something-client.log
I need to add some lines (these lines are constant) so that the files end with "client.log"
line 1
line 2
line 3
line 4
add these four lines to the end of the files with "client.log"
Yes. I found that the open () "a" function will provide the desired output. but how to select the correct file that is there, exclude server.log and select client.log?
and for files - "server.log"
I needed to add after the "After-this" keyword. The "server.log" file has several "After-this" entries. I need to find the first "After-this" entry and add the above four lines, keeping the remaining file as it is.
Any help would be greatly appreciated :) Thanks in advance.
a source to share
not verified
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
a source to share