python - How do I write to the middle of a text file while reading its contents? -
first of helping me out moving files , helping me in tcl script.
small doubt had python code.. below..
import os import shutil data =" set filelid [open \"c:/sanity_automation/work_project/output/smoketestresult\" w+] \n\ puts $filelid \n\ close $filelid \n" path = "c:\\sanity_automation\\routertester900systemtest" if os.path.exists(path): shutil.rmtree('c:\\sanity_automation\\routertester900systemtest\\') path = "c:\\program files (x86)" if os.path.exists(path): src= "c:\\program files (x86)\\abc\\xyz\\quicktest\\scripts\\routertester900\\diagnostic\\routertester900systemtest" else: src= "c:\\program files\\abc\\xyz\\quicktest\\scripts\\routertester900\\diagnostic\\routertester900systemtest" dest = "c:\\sanity_automation\\routertester900systemtest\\" shutil.copytree(src, dest) log = open('c:\\sanity_automation\\routertester900systemtest\\routertester900systemtest.app.tcl','r+') log_read=log.readlines() x="closealloutputfile" open('c:\\sanity_automation\\routertester900systemtest\\routertester900systemtest.app.tcl', 'a+') fout: line in log_read: if x in line: fout.seek(0,1) fout.write("\n") fout.write(data)
this code copying files 1 location another, searching keyword in particular file , writing data file working...
my doubt whenever write.. writes end of file instead of current location...
example: say.. copied file program files sanity folder , searched word "closealloutputfile" in 1 of copied file. when word found, should insert text in position instead of end of file.
a simple way add data in middle of file use fileinput
module:
import fileinput line in fileinput.input(r'c:\sanity_automation\....tcl', inplace=1): print line, # preserve old content if x in line: print data # insert new data
from the fileinput
docs:
optional in-place filtering: if keyword argument inplace=1 passed fileinput.input() or fileinput constructor, file moved backup file , standard output directed input file (if file of same name backup file exists, replaced silently). makes possible write filter rewrites input file in place. if backup parameter given (typically backup='.'), specifies extension backup file, , backup file remains around; default, extension '.bak' , deleted when output file closed.
to insert data filename
file while reading without using fileinput
:
import os tempfile import namedtemporaryfile dirpath = os.path.dirname(filename) open(filename) file, \ namedtemporaryfile("w", dir=dirpath, delete=false) outfile: line in file: print >>outfile, line, # copy old content if x in line: print >>outfile, data # insert new data os.remove(filename) # rename() doesn't overwrite on windows os.rename(outfile.name, filename)
Comments
Post a Comment