如何解析CSV文件,更新字段然后保存 [英] How to parse a CSV file, update a field, then save

查看:75
本文介绍了如何解析CSV文件,更新字段然后保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要阅读CSV文件,更新字段,然后保存更改.除了将更改保存到我要更新的字段之外,我一切正常,

I need to read a CSV file, update a field, then save the changes. I have everything working fine except saving my changes to the field I'm updating:

require 'csv'
@parsed_file = CSV::Reader.parse(File.open("#{RAILS_ROOT}/doc/some.csv"))
@parsed_file.each_with_index  do |row, x|
  address = row[5]
  l = Location.address_find(address)
  if l != nil
    puts "#{l.name} at #{l.address}"
    row[14] = l.store_code
    puts row[14]
  else
    puts "No matching address Found!!!"
  end
  #What do I do here? Something like this? CSV::Writer.generate(@parsed_file) 
end

我在这里做什么?如何保存所做的更改并更新文件?

What do I do here? How do I save the changes I made and update the file?

推荐答案

我要做的是将更新的记录写入新文件,然后,如果需要,在程序完成后可以删除旧文件并重命名新文件具有原始文件名.

What I would do is write the updated records to a new file and then, if you want, after you have finished your program can delete the old file and rename the new file to have the original file name.

为此,我将在each_with_index循环之外的代码顶部打开输出文件.例如

To do this I would open the output file at the top of your code, outside the each_with_index loop. e.g.

csv_out = CSV::Writer.generate(File.open('new.csv', 'wb'))

然后在each_with_index循环中,您可以像这样将当前行写入新文件:

Then inside your each_with_index loop you can write the current row to the new file like this:

csv_out << row

然后最后您可以关闭新文件:

Then at the end you can close the new file:

csv_out.close


如注释中所述,CSV::Writer不再在标准库中.使用较新的CSV.foreach(用于阅读)和CSV.open(用于书写)的代码的等效版本为:


As mentioned in the comments, CSV::Writer is no longer in the standard library. An equivalent version of the code using the newer CSV.foreach (for reading) and CSV.open (for writing) is:

CSV.open("path/to/file.csv", "wb") do |csv_out|
  CSV.foreach("#{RAILS_ROOT}/doc/some.csv") do |row|
    address = row[5]
    l = Location.address_find(address)
    if l != nil
      puts "#{l.name} at #{l.address}"
      row[14] = l.store_code
      puts row[14]
    else
      puts "No matching address Found!!!"
    end
    csv_out << row 
  end
end

这篇关于如何解析CSV文件,更新字段然后保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆