如何使用python替换文件中的特定文本行。看看我们是否有一个名为“File1.tcl”的文件。并找到一个特定的单词“:: AgtQtl :: CloseAllOutputFiles”。如果发现替换为以下文字。 any1可以帮我解决这个问题......
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
}
在此代码中...查找此行文本“:: AgtQtl :: CloseAllOutputFiles”
如果找到..替换为这行代码
set filelid [open "C:/Sanity_Automation/Work_Project/Output/smokeTestResult" w+]
puts $filelid
close $filelid
答案 0 :(得分: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()
希望它有所帮助。可能还有其他更好的方法。如果文件很大,此代码效率不高。