Ruby - 如何使用脚本输出编写新文件

the*_*gah 24 ruby

我有一个简单的脚本,可以进行一些搜索和替换.这基本上是这样的:

File.open("us_cities.yml", "r+") do |file|
  while line = file.gets
  "do find a replace"
  end
  "Here I want to write to a new file"
end
Run Code Online (Sandbox Code Playgroud)

如您所见,我想用输出写一个新文件.我怎样才能做到这一点?

小智 36

输出到新文件可以像这样完成(不要忘记第二个参数):

output = File.open( "outputfile.yml","w" )
output << "This is going to the output file"
output.close
Run Code Online (Sandbox Code Playgroud)

所以在你的例子中,你可以这样做:

File.open("us_cities.yml", "r+") do |file|
  while line = file.gets
    "do find a replace"
  end
  output = File.open( "outputfile.yml", "w" )
  output << "Here I am writing to a new file"
  output.close      
end
Run Code Online (Sandbox Code Playgroud)

如果要附加到文件,请确保将输出文件的开头放在循环之外.


the*_*gah 6

首先,您必须创建一个新文件,例如newfile.txt

然后将脚本更改为

File.open("us_cities.yml", "r+") do |file|
  new_file = File.new("newfile.txt", "r+")
  while line = file.gets
  new_file.puts "do find a replace"
  end
end
Run Code Online (Sandbox Code Playgroud)

这将使输出生成一个新文件