Skip to content

csv.reader do not preserve line return in quoted values #158837

Description

@un-pogaz

Bug report

As the title say, when reading a CSV file, the line return are not preserved inside a quoted value, even if the reader correctly eager until the end of the quoted value. The line return are just gone.

For the given source file:

"Id (id)","Authors (authors)","Title (title)","Comments (comments)"
"195","Léo Malet","120, Rue de la Gare","Written in 1942.
120, Rue de la Gare was published the following year.

It marked a sort of literary milestone."

The current and simple use of a csv.reader will result to:

[
    ['Id (id)', 'Authors (authors)', 'Title (title)', 'Comments (comments)']
    ['195', 'Léo Malet', '120, Rue de la Gare', 'Written in 1942.120, Rue de la Gare was published the following year.It marked a sort of literary milestone.']
]

expected result:

[
    ['Id (id)', 'Authors (authors)', 'Title (title)', 'Comments (comments)']
    ['195', 'Léo Malet', '120, Rue de la Gare', 'Written in 1942.\n120, Rue de la Gare was published the following year.\n\nIt marked a sort of literary milestone.']
]

Here, as proof of concept, a simple functional python implementation that return the correct values with the preserved line return:

def quoted_line_return(csvfile: Iterable[str]) -> Iterator[str]:
    in_quote = False
    row = []
    for line in csvfile:
        row.append(line)
        if bool(line.count('"') % 2):  # test odd quote in the line
            if in_quote:
                in_quote = False
            else:
                in_quote = True
        if not in_quote:
            yield '\n'.join(row)
            row.clear()

reader = csv.reader(quoted_line_return(lines_src))

CPython versions tested on:

3.14

Operating systems tested on:

Linux

Linked PRs

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirtype-bugAn unexpected behavior, bug, or error

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions