Sagar Grover
Sagar Grover

Reputation: 65

File deleted each time

I have a ruby controller

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

So in this I am reading from a file like

    %12th%main%
    %100 feet%
    %12th%main%
    %12th%main%
    %12th%main%
    %100 feet%

In the ruby console I can see all the queries getting executed but in query_output.txt I only get the output of last query. What am I doing wrong here?

Upvotes: 0

Views: 30

Answers (1)

nathanvda
nathanvda

Reputation: 50057

You use filemode w which will re-create the output file every time (so you will write into an empty file). Instead open your file as follows:

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

a stands for append. It will open or create the file, and append at the back.

For more info concerning file-modes: http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html

Upvotes: 1

Related Questions