加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 02:08:12 所属栏目:百科 来源:网络整理
导读:编辑:我不需要使用相同的文件.可以创建新文件.我需要的是包含与原始列和新列相同的列和行的结果,但顺序相同. 我一直在尝试使用Ruby将列附加到现有的CSV文件,但是我收到了一个我不理解的错误.这是我的代码: CSV.foreach("test.csv","a+") do | row |c = Cur
编辑:我不需要使用相同的文件.可以创建新文件.我需要的是包含与原始列和新列相同的列和行的结果,但顺序相同.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读