0

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

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

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
4

1 回答 1

2

如果问题发生变化,我将对其进行编辑,因为目前尚不清楚;我没有看到目录有任何变化,所以我假设用户:

  1. 更改那里某处的目录。
  2. 想要继续将信息附加到同一个文本文档。

如果这是真的,答案将是使用文本文件的绝对路径:

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

如果你正在做这些 long sleeps,那可能是个问题,但你也可以坚持这条路:

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% 确定问题在问什么,但解决方案要么使用绝对路径保留文件句柄,要么在写入文本文件之前更改回原始目录.

于 2013-04-03T11:38:50.247 回答