简体   繁体   English

有没有一种方法可以使Ruby CSV gem在Windows(CR LF)行尾生成CSV?

[英]Is there a way to make Ruby CSV gem generate CSVs with Windows (CR LF) End Of Lines?

For some reason CSV gem is generating CSVs with Unix EOL (see screenshot) here: https://www.dropbox.com/s/4re7tpp4pj9psov/ice_screenshot_20171230-162304.png?dl=0 Screenshot made in Notepad++ (View all Characters) 出于某种原因,CSV宝石使用Unix EOL生成CSV(请参见屏幕快照), 网址为https ://www.dropbox.com/s/4re7tpp4pj9psov/ice_screenshot_20171230-162304.png?dl =0用记事本++制作的屏幕截图(查看所有字符)

Code I use: 我使用的代码:

require 'csv'

all_the_things = []

all_the_things << ["item1.1","item1.2","item1.3"]
all_the_things << ["item2.1","item2.1","item2.1"]
all_the_things << ["item3.1","item3.1","item3.1"]

CSV.open("test.csv", "wb" ) do |row|
  row << ["Column1", "Column2", "Column3"] #just headers
    all_the_things.each do |data|
      row << data
    end
end

Is there a way to make it use Windows EOL (CR LF) instead of UNIX (LF) ones ? 有没有办法使它使用Windows EOL(CR LF)而不是UNIX(LF)?

I'm using Windows 10, and if I just output some lines to file using puts everything working just fine (albeight managing proper data structure without CSV gem is nightmare): 我正在使用Windows 10,并且如果我只是使用输出某些行到文件中,那么一切都将正常运行(在没有CSV gem的情况下管理正确的数据结构的高度是噩梦):

....
   File.open("test.csv", "w") do |line|
    myarray.each do |data|
      line.puts data
    end
end

Thank you in advance for any ideas and Happy New Year ! 预先感谢您的任何想法和新年快乐!

As it is clearly stated in the documentation , one might use the row_sep option to specify the row separator: 正如文档中明确指出的那样,可以使用row_sep选项指定行分隔符:

require 'csv'
#                               ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓ here
CSV.open("/tmp/file.csv", "wb", row_sep: "\r\n") do |csv|
  csv << %w|1 2 3 4|
  csv << %w|a b c d|
end

Also, there is no “CSV gem,” it's ruby standard library. 此外,没有“ CSV宝石”,这是ruby标准库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM