I am generating a CSV file from Ruby, and the system that is receiving the data can’t accept a blank line at the bottom.
However, after I’ve appended all my lines (that end with CRLF) the last row still has the CFLF, so the receiving system think that there is a blank lasy line.
I solved it by doing this (hackish) code to open and truncate the file:
size = File.size(filename)
File.truncate(filename, size-3)
Am I missing some feature in ruby CSV to not add CRLF if it is the last line?
My code for writing the CSV is:
csv = CSV.open(filename, "w", {:row_sep => "\r\n"})
.. code to create an array of cols ..
csv << cols
I tried converting this to use a string, rather then a file. But I had no success doing it. I kept getting an error using the << operator.
UPDATE: It turns out I had the wrong question…
It’s been a while but I finally figured out what was going on. The host system I was uploading too can handle the newline at the end of the file – it was that Ruby CSV was putting in the wrong newline characters: \r\r\n instread of \r\n! It is doing this if I write as a text file. If I write as a binary file the problem is solved.
In case anyone else sees the same issue, this was my Ruby:
csv = CSV.open(filename, "w", {:row_sep => "\r\n"}) # actually writes \r\r\n
Binary mode fixes it:
csv = CSV.open(filename, "wb", {:row_sep => "\r\n"}) # correctly writes \r\n
If you are getting the CSV as a string before writing it, you can use
String#chompto remove a trailing newline.If you are writing the file by using:
…then you are adding a newline yourself, and can avoid it with:
If you supply your actual code for generating and writing the CSV, we can help you further and more precisely.