解析CSV文件,更新字段,然后保存 [英] Parse a CSV file, update a field, then save
问题描述
我需要一个CSV文件!更新字段!然后保存更改。除了将更改保存到我正在更新的字段之外,我还有一切正常工作:
I need to rad 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
(用于书写)的代码的等效版本是:
Updated version: 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屋!