2010-03-13 77 views
22

我有一个简单的脚本来完成一些搜索和替换。 这基本上是: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 

正如你可以看到我想要写与输出的新文件。我怎样才能做到这一点?

回答

32

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

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 

如果您想追加到文件中,请确保将输出文件的打开位置放在循环之外。

5

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

这将使一个新的文件与输出

相关问题