0

How to replace a particular line of text in a file using python. See if we have a called "File1.tcl". and locate a particular for word "::AgtQtl::CloseAllOutputFiles". If found replace with below text. Can any1 help me out with this...

File1.tcl :

AgtQtl::SetupOutputFiles
    if { [AddAllPorts] } {
        set result [PreparePorts]
        InitPortInfo
        #
        # start the test
        #
        if { [AgtQtl::GetScriptMode] != "COMMANDLINE" } {
            ::TestGui::ShowResult None black gray -noraise
        }
        GenerateReportSection HEADER
        if { $result } {
            if [AddSubinterfaces] {
                RunTestLoop
            } else {
                set message [list "Add sub-interfaces" "FAIL"]
                GenerateReportSection BODYRECORD $message
                lappend statLog $message
            }
        } else {
            set message [list "Prepare ports" "FAIL"]
            GenerateReportSection BODYRECORD $message
            lappend statLog $message
        }
        set appData(testStopTime) [clock seconds]
        set testPassFailMsg [DeterminePassFail]
        if { $testPassFailMsg == "" } {
            set testPassFailMsg "PASSED"
        }
        set appData(testPassFailMsg) $testPassFailMsg
        GenerateReportSection FOOTER
        ::TestApp::StopTest
    }
}
AgtTsuTestState TEST_STOPPED
if { [AgtQtl::GetScriptMode] != "COMMANDLINE" } {
    switch $testPassFailMsg {
    PASSED {
        set testPassFailMsg "PASS"
        set fgColour black
        set bgColour green
       }
    default  {
        set testPassFailMsg "FAIL"
        set fgColour black
        set bgColour red
       }
    }
    ::TestGui::ShowResult $testPassFailMsg $fgColour $bgColour
}

::AgtQtl::CloseAllOutputFiles

return $result

}

in this code... look for this line of text "::AgtQtl::CloseAllOutputFiles"

if found.. replace with this line of code

set filelid [open "C:/Sanity_Automation/Work_Project/Output/smokeTestResult" w+]
puts $filelid
close $filelid

1 Answer 1

1

Easiest way is to write content to different file as you scan through it. Here is the code:

replace_with = """
set filelid [open "C:/Sanity_Automation/Work_Project/Output/smokeTestResult" w+]
puts $filelid
close $filelid
"""
search = "AgtQtl::CloseAllOutputFiles"

fd1 = open('so.tcl')
fd2 = open('so1.tcl', 'w')

for line in fd1.readlines():
    if line.find(search) > -1:
        fd2.write(replace_with)
    else:
        fd2.write(line)

fd1.close()
fd2.close() 

Hope it helps. There might be other better ways. This code is not efficient if the file is big.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.