How to append columns to existing CSV using Ruby 2.2.2 -
edit: don't need use same file. new file can created. need result contain same columns , rows in original plus new columns, in same order.
i've been trying append columns existing csv file ruby i'm getting error don't understand it. here's code:
csv.foreach("test.csv", "a+") | 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 | w | row << w['short_name'] end end end
on csv.foreach... part i've tried csv.foreach('file.csv', 'a+'), csv.foreach('file.csv', 'wb'), csv.foreach('file.csv', 'a') , nothing seemed work.
then dawned on me maybe should using open instead:
file = csv.open('test.csv', 'wb') file.each | 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 | w | row << w['short_name'] end end end but didn't work either.
what missing? thanks!
why don't try opening file different mode?
looks looking for:
csv.open('test.csv', 'r+') |row| row << ['existing_header1','existing_header2','new_header'] end this in fact overwrite first line 1 specified. works because 'r+' reads beginning of file, , overwrites existing rows goes through file. in case need change first 1 :)
here's list of useful modes can use open file. cheers.
"r" -- read beginning of file
"r+" -- read/write beginning of file
"w" -- write only, overwriting entire existing file or creating new 1 if none existed
"w+" -- read/write, overwriting entire existing file or creating new 1 if none existed
"a" -- write only, starting @ end of existing file or creating new 1 if none existed
"a+" -- read/write, starting @ end of existing file or creating new 1 if none existed
source: opening modes
Comments
Post a Comment