Skip to content

CsvFileWriter.writeRows writes line terminator even when passed list or sequence is empty #122

@robert-medina-factorypal

Description

Describe the bug

CsvFileWriter.writeRows(rows: List<List<Any?>>) and CsvFileWriter.writeRows(rows: Sequence<List<Any?>>) write configured ctx.lineTerminator when the passed list or sequence argument has no elements. This results in a CSV file with empty lines in between, e.g.:

a,b,c
foo1,bar1,baz1
foo2,bar2,baz2

foo3,bar3,baz3
foo4,bar4,baz4

To Reproduce

  1. Open a CSV writer.
  2. Call CsvFileWriter.writeRows() with either an empty list or an empty sequence.

Here is a code snippet on how to reproduce the issue:

val headers = listOf("a","b","c")
val rows1 = listOf(
    listOf("foo1","bar1","baz1"),
    listOf("foo2","bar2","baz2")
)
val rows2 = emptyList<List<Any?>>()
val rows3 = listOf(
    listOf("foo3","bar3","baz3"),
    listOf("foo4","bar4","baz4")
)
csvWriter { lineTerminator = "\n" }.open("example.csv") {
    writeRow(headers)
    writeRows(rows1)
    writeRows(rows2) //Here the CSV file will have the configured line terminator added even though the list is empty.
    writeRows(rows3)
}

Expected behavior

A CSV file without empty rows in between. For example:

a,b,c
foo1,bar1,baz1
foo2,bar2,baz2
foo3,bar3,baz3
foo4,bar4,baz4

Environment

  • kotlin-csv version 1.9.0
  • java version 17
  • OS: macOS

I will try to create a PR with the fix once I have some time.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions