Ruby 读写带引号的 CSV

标签 ruby csv

我想读取一个 csv 行,更新一个字段,然后用引号再次输出该行。

Row Example Input => "Joe", "Blow", "joe@blow.com"
Desired Row Example Output => "Joe", "Blow", "xxxx@xxxx.xxx"

My script below outputs => Joe, Blow, xxxx@xxxx.xxx

它丢失了我想保留的双引号。

我已经尝试了各种选择,但到目前为止没有任何乐趣..有什么建议吗?

非常感谢!

require 'csv'

CSV.foreach('transactions.csv',
            :quote_char=>'"',
            :col_sep =>",", 
            :headers => true, 
            :header_converters => :symbol ) do |row| 

row[:customer_email] = 'xxxx@xxxx.xxx'

puts row

end

最佳答案

CSV 字段中的引号通常是不必要的,除非字段本身包含分隔符或换行符。但您可以强制 CSV 文件始终使用引号。 For that, you need to set force_quotes => true :

CSV.foreach('transactions.csv',
            :quote_char=>'"',
            :col_sep =>",", 
            :headers => true, 
            :force_quotes => true,
            :header_converters => :symbol ) do |row| 

关于Ruby 读写带引号的 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17079873/

相关文章:

javascript - 在 Ruby 中实现类似 JavaScript 的闭包

ruby-on-rails - 用散列对数组求和

python - 在django模型中插入CSV数据,空值

asp.net-mvc - Controller 循环 mvc asp.net 中的进度条

ruby-on-rails - 运行索引迁移时,Rails 是否索引现有记录?

ruby-on-rails - 为什么不使用全局(美元符号 $)变量?

r - 如何使用多字节分隔符将文本文件读入 GNU R?

php - MySQL PHP CSV 文件导出

excel - 即使单元格为空,使用 VBA 创建的 CSV 文件末尾也有空白行

ruby-on-rails - 从多维数组中删除 "empty"个元素