ruby - 如何使用 Ruby 2.2.2 将列附加到现有 CSV

标签 ruby csv

编辑:我不需要使用同一个文件。可以创建一个新文件。我需要的是包含与原始列和新列相同的列和行的结果,但顺序相同。

我一直在尝试使用 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

来源:Opening modes

关于ruby - 如何使用 Ruby 2.2.2 将列附加到现有 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31271649/

相关文章:

ruby-on-rails - 如何使用 render_to_string 在 lib ruby​​ 类中呈现部分

ruby - 在 Ruby 中编写文件更改监听器

ruby-on-rails - 如何对 mongodb/mongoid 脚本进行基准测试,以比较两种不同的查询技术

Postgresql:带转义换行符的 CSV 导出

r - 如何使用来自 csv 文件的实际观测值正确注释堆栈条形图?

javascript - JS Highchart 导入 CSV 数据

java - 使用 split 使用分隔符选项卡 "\t"在 Java 中解析字符串

ruby-on-rails - 连接 Rails 3.1 与多个数据库

ruby-on-rails - 无法打开与本地主机 :9200 - Rails on Docker 的 TCP 连接

csv - 将 Kaggle csv 从下载 url 导入到 Pandas DataFrame