Edit: I don't need to use the same file. A new file can be created. What I do need is the result to contain the same columns and rows as in the original plus the new columns, but in the same order.
I've been trying to append columns to an existing CSV file with Ruby but I'm getting an error that I don't understand it. Here's my code:
CSV.foreach("test.csv", "a+") do | row |
c = Curl::Easy.perform("http://maps.googleapis.com/maps/api/geocode/json?latlng=#{row[1]},#{row[0]}&sensor=false")
result = JSON.parse(c.body_str)
if result['status'] != 'OK'
sleep(5)
else
row << result['results'][0]['formatted_address']
result['results'][0]['address_components'].each do | w |
row << w['short_name']
end
end
end
On the CSV.foreach...
part I've tried CSV.foreach('file.csv', 'a+')
, CSV.foreach('file.csv', 'wb')
, CSV.foreach('file.csv', 'a')
and nothing seemed to work.
Then it dawned on me that maybe I should be using open
instead:
file = CSV.open('test.csv', 'wb')
file.each do | csv |
c = Curl::Easy.perform("http://maps.googleapis.com/maps/api/geocode/json?latlng=#{row[1]},#{row[0]}&sensor=false")
result = JSON.parse(c.body_str)
if result['status'] != 'OK'
sleep(5)
else
row << result['results'][0]['formatted_address']
result['results'][0]['address_components'].each do | w |
row << w['short_name']
end
end
end
But that didn't work either.
What am I missing? Thanks!