使用RUBY编写CSV并删除双倍间距

时间:2014-01-10 04:39:37

标签: ruby parsing csv

我正在阅读文本文件并写入CSV。但是,CSV每隔一行写一行。我已经尝试过更改选项,gsub,chomp - 但它的接缝就像我没有看到的回车线。

#make CSV 
#read text file and write contents to it

File.open(new_csv_path, headers: true, write_headers: true) do |csv|

  #make headers
  if csv.tell = 0
    csv << "first_column, second_column, third_columnn\n"
  end

  File.foreach(text_file) do |text|
    csv << text
  end
end

file.txt如下所示:

What type of loan are you currently in? (VA, FHA, Conventional)

What is your current interest rate? 6.25

Who is your current lender?

Do you occupy the home as your primary residence?

output.csv看起来像这样:

What type of loan are you currently in? (VA, FHA, Conventional)
                                             #i need to delete this line
What is your current interest rate? 6.25

Who is your current lender?

Do you occupy the home as your primary residence?

正如你所看到的那样打印,但还有一条额外的线条。如何删除行?我已经阅读了其他帖子,但我没有看到一个处理这个双间距问题。如果我错过了请发给我讨论主题。感谢

2 个答案:

答案 0 :(得分:0)

一些可能的错误

  File.foreach(text_file) do |text|
    csv << line   <-------- shouldn't this be |text|
  end

为了使其保持一致,您可以chompstrip换行,然后相应地添加

答案 1 :(得分:0)