Ruby读和写带引号的CSV [英] Ruby Read and Write CSV with Quotes
本文介绍了Ruby读和写带引号的CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想读取一个csv行,更新一个字段,然后再次用引号输出该行.
I'd like to read in a csv row, update one field then output the row again with quotes.
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
它丢失了我想保留的双引号.
It loses the double quotes which I want to retain.
我尝试了各种选择,但到目前为止没有任何乐趣..有什么建议吗?
I've tried various options but no joy so far .. any tips?
非常感谢!
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文件始终使用引号. 为此,您需要设置force_quotes => true
:
Quotes in CSV fields are usually unnecessary, unless the field itself contains a delimiter or a newline character. But you can force the CSV file to always use quotes. 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文