我想多次将文本写入文件(追加)。当前我正在使用:在这种情况下,我捕获了结束时间和开始时间的系统时间。
File.open("c:\\temp\\myfile.txt", "w").write("My first input: #{endtime-starttime} seconds \n")
我想在脚本的不同位置多次进行此操作,但是它似乎无法正常工作。文本文件似乎正在覆盖自身。脚本中是否可以在不同的行中写入文本?
谢谢,斯科特
这是一个更好的例子
#------------------------------------------------------------------------------------------------ ---------------------
#Log into System
#---------------------------------------------------------------------------------------------------------------------
starttime=Time.new
LoginButton = driver.find_element(:xpath, "/html/body/div[3]/div/div[2]/ul/li[3]/a")
LoginButton.click
option = driver.find_element(:xpath, "/html/body/div/div[1]/div/div[3]/div[1]/form/div[3]/ul/li[1]/input")
option.send_keys"blah"
option = driver.find_element(:id, "password")
option.send_keys"blah"
option = driver.find_element(:xpath, "/html/body/div/div[1]/div/div[3]/div[1]/form/div[3]/ul/li[3]/input")
option.click
endtime=Time.new
puts"Login: #{endtime-starttime} seconds"
File.open("c:\\temp\\myfile.txt", "w").write("Login: #{endtime-starttime} seconds \n")
puts"Login Done"
#---------------------------------------------------------------------------------------------------------------------
#Performance Test Course
#---------------------------------------------------------------------------------------------------------------------
starttime=Time.new
driver.switch_to.frame "contentFrame" #Sets focus on the "UR Courses Online Module"
option = driver.find_element(:link_text, "Performance Test Course")
option.click
endtime=Time.new
puts"Performance Test Course Link: #{endtime-starttime} seconds"
File.open("c:\\temp\\myfile.txt", "w").write("Performance Test Course Link: #{endtime-starttime} seconds \n")
puts"Performance Test Course Done"
您可能希望将打开的文件对象存储在变量中,以便在向文件中写新行时将其写到末尾。您之前的代码将打开给定的文件,在文件中的位置0处写一行,然后关闭文件。
file = File.open("text.txt", "w")
file.write "hello world"
或者,您可以使用“ a”标志打开文件以在文件末尾进行写操作。
File.open("c:\\temp\\myfile.txt", "a+").write("My first input: #{endtime-starttime} seconds \n")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句