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 

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

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

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

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

 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 

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

首先,您必须创建一个新文件,例如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 

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