编辑:我不需要使用同一个文件。可以创建一个新文件。我需要的是包含与原始列和新列相同的列和行的结果,但顺序相同。
我一直在尝试使用 Ruby 将列附加到现有的 CSV 文件,但我收到一个我不理解的错误。这是我的代码:
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
结束
在 CSV.foreach...
部分,我尝试了 CSV.foreach('file.csv', 'a+')
, CSV。 foreach('file.csv', 'wb')
, CSV.foreach('file.csv', 'a')
似乎没有任何效果。
然后我突然意识到也许我应该改用 open
:
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
但这也没有用。
我错过了什么?谢谢!
最佳答案
你为什么不尝试用不同的模式打开文件?
看起来这就是您要找的:
CSV.open('test.csv', 'r+') do |row|
row << ['existing_header1','existing_header2','new_header']
end
这实际上会覆盖您刚刚指定的第一行。它之所以有效,是因为“r+”从文件的开头读取,并在遍历文件时覆盖所有现有行。但在这种情况下,您只需要更改第一个 :)
这里列出了可用于打开文件的有用模式。干杯。
"r" -- read only from the beginning of the file
"r+" -- read/write from the beginning of the file
"w" -- write only, overwriting the entire existing file or creating a new one if none existed
"w+" -- read/write, overwriting the entire existing file or creating a new one if none existed
"a" -- write only, starting at the end of existing file or creating a new one if none existed
"a+" -- read/write, starting at the end of existing file or creating a new one if none existed
关于ruby - 如何使用 Ruby 2.2.2 将列附加到现有 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31271649/