我正在使用 ruby CSV 模块读取 csv 文件。
csv 文件中的值之一的格式是 XXX_XXXXX,其中 X 是数字。实际上,我将此值视为字符串,但 CSV 模块将这些值读取为 XXXXXXXX,作为数字,这是我不想要的。
我目前使用的选项
f = CSV.read('file.csv', {:headers => true, :header_converters => :symbol, :converters => :all} )
有没有办法告诉 CSV 不要那样做?
f = CSV.read('file.csv', {:headers => true, :header_converters => :symbol)}
省略:converters => :all; 尝试(除其他外)将所有具有数字外观的字符串转换为数字。
:convertors => all 会导致这种情况,请尝试以下操作
require "csv"
CSV.parse(DATA, :col_sep => ",", :headers => true, :converters => :all).each do |row|
puts row["numfield"]
end
__END__
textfield,datetimefield,numfield
foo,2008-07-01 17:50:55.004688,123_45678
bar,2008-07-02 17:50:55.004688,234_56789
# gives
# 12345678
# 23456789
和
CSV.parse(DATA, :col_sep => ",", :headers => true).each do |row|
puts row["numfield"]
end
__END__
textfield,datetimefield,numfield
foo,2008-07-01 17:50:55.004688,123_45678
bar,2008-07-02 17:50:55.004688,234_56789
# gives
# 123_45678
# 234_56789