每次都删除文件

File deleted each time

我有一个 ruby 控制器

def new
    counter = 1
    fileW = File.new("query_output.txt", "w") 
    file = File.new("query_data.txt", "r")
    while (line = file.gets)
        puts "#{counter}: #{line}"
        query = "select name,highway from planet_osm_line where name ilike '" +line+"'"
        @output = PlanetOsmLine.connection.execute(query)   
        @output.each do |output|
            fileW.write(output['highway'] + "\n")
        end
        counter = counter + 1
    end
    file.close
    query = ""
   @output = PlanetOsmLine.connection.execute(query)
 end

因此,我正在从

这样的文件中读取
    %12th%main%
    %100 feet%
    %12th%main%
    %12th%main%
    %12th%main%
    %100 feet%

在 ruby 控制台中,我可以看到所有正在执行的查询,但在 query_output.txt 中,我只能看到最后一个查询的输出。我在这里做错了什么?

您使用文件模式 w 每次都会重新创建输出文件(因此您将写入一个空文件)。而是按如下方式打开文件:

fileW = File.new("query_output.txt", "a")

a代表append。它将打开或创建文件,并在后面追加。

有关文件模式的更多信息:http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html