0

如何使用 python 替换文件中的特定文本行。看看我们是否有一个名为“File1.tcl”。并找到一个特定的单词“::AgtQtl::CloseAllOutputFiles”。如果找到替换为以下文本。任何人都可以帮我解决这个问题...

文件1.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

}

在这段代码中......寻找这行文本“::AgtQtl::CloseAllOutputFiles”

如果找到.. 替换为这行代码

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

1 回答 1

1

最简单的方法是在扫描时将内容写入不同的文件。这是代码:

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() 

希望能帮助到你。可能还有其他更好的方法。如果文件很大,此代码效率不高。

于 2013-05-15T08:46:07.883 回答