Skip to content

Redirected output on Windows: CSV rows end in CR CR LF and text is not UTF-8, so exports can't be inserted again #981

Backlog

Description

@Zephyr4772

On Windows, output that is redirected to a file or pipe has two problems, and together they mean a CSV export can't be inserted again.

  1. --csv and --tsv rows end in \r\r\n. csv.writer writes \r\n itself, and the text-mode stdout translates its \n again. Python's csv docs ask for newline='' for this reason. This happens even with the PYTHONUTF8=1 workaround from the docs.
  2. The output uses the locale encoding (cp1252), not UTF-8. Characters outside cp1252 raise UnicodeEncodeError partway through, leaving a truncated file. Characters inside it are written as cp1252 bytes, which sqlite-utils insert (UTF-8 by default) can't read. Since JSON output no longer escapes non-ASCII characters, new --ascii option #777 this also applies to the default JSON output.

To reproduce (sqlite-utils 4.2.2, Python 3.12, Windows 11, no PYTHONUTF8), with in.csv containing name,city, José,Zürich, Renée,Köln:

sqlite-utils insert a.db t in.csv --csv
sqlite-utils a.db "select * from t" --csv > exported.csv
sqlite-utils insert b.db t exported.csv --csv

The last command fails with ... It's often worth trying: --encoding=latin-1, because exported.csv holds Jos\xe9 (cp1252).

With PYTHONUTF8=1 set, the encoding is right but the rows are not: the file starts name,city\r\r\nJosé,Zürich\r\r\n, Python's csv.reader returns an empty row after every row, and inserting it again fails with a traceback ending in ValueError: Tables must have at least one column.

With non-Latin text (प्रिया,मुंबई), --csv, --table and the default JSON output all stop with UnicodeEncodeError: 'charmap' codec can't encode characters.

Suggested fix: in the cli group callback, reconfigure stdout to UTF-8 when it is redirected (not a terminal), unless PYTHONIOENCODING asks for something else, and set newline="" on stdout before handing it to csv.writer. Neither changes anything on Linux or macOS, where redirected output is already UTF-8 and newlines are not translated. I have this ready as a PR, with tests that emulate a Windows redirected stream so they fail without the fix on every CI platform.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions