如何更改目录但仍写入现有文件?

时间:2013-04-03 11:07:03

标签: ruby

我编写了一个创建文本文件的脚本,并保存了我需要保存的所有内容。问题出现在我进行一个循环并更改目录以上载另一个目录中的文件之后,但文本文件保留在旧目录中。

如何更改目录但仍写入文本文件?这是我的代码:

kolekcija.each do |fails|
  @b.send_keys :tab
  @b.span(:class => "btnText", :text => "Save", :index => 1).when_present.click
  @b.frame(:id, "uploadManagerFrame").table(:id, "ctrlGetUploadedFiles_gvUploadedFiles").wait_until_present
  sleep 30

  # I need to edit it so it opens the TXT file in its existing location
  output = File.open("#{Time.now.strftime("%Y.%m.%d")} DemoUser.txt", "a") 
  output.puts ""
  output.puts "Korpusā ielādētais fails:  #{File.basename(@fails)} augšuplādēts sekmīgi..."
  output.close
  progress.increment
end

1 个答案:

答案 0 :(得分:2)

如果问题发生变化,我会编辑它,因为它不清楚;我没有看到目录的任何变化,所以我假设用户:

  1. 在那里的某处更改目录。
  2. 想要继续将信息附加到同一文本文档中。
  3. 如果这是真的,那么答案将是使用文本文件的绝对路径:

    file = File.open("/full/path/to/file", "a")
    kolekcija.each do |fails|
      # ...
      file.puts "some stuff"
      # ...
    end
    file.close
    

    如果您正在执行这些漫长的sleep,那可能会出现问题,但您也可以坚持这条道路:

    path = "/full/path/to/file"
    kolekcija.each do |fails|
      # ...
      file = File.open(path, "a")
      file.puts "some stuff"
      file.close    
      # ...
    end
    

    或者在脚本部分中使用Dir.chdir块,将目录更改为其他内容并返回:

    Dir.chdir(ENV["HOME"])  # now you're in your home directory ~
    Dir.chdir("files") do   # now in ~/files
      upload_files
    end                     # aaand you're back home
    file = File.open("/full/path/to/file", "a")
    file.puts "stuff"
    file.close
    

    我承认我不是100%肯定问题是什么,但是解决方案是要么继续使用文件句柄,使用绝对路径,要么在写入之前更改回原始目录文本文件。