Fix CSV line break problems

Why CSV files break rows apart or merge them, how to tell line-ending issues from embedded newlines, and when to flatten line breaks for TSV or plain text.

A CSV line break problem usually looks like one of three things: a single record split across several rows, several records merged into one, or stray characters at the end of each value. These look similar but have different causes. Some fixes, such as stripping every carriage return, can damage data that was actually fine. This review covers what each fix changes, how to diagnose the cause, and when a flattened plain-text version is the better choice.

About the evidence: no test files, tool measurements or product-specific results were available for this article. The guidance below draws on documented conventions, mainly the CSV description in RFC 4180 and the Python csv module documentation. Behavior in a particular spreadsheet, database or import tool should be checked with a small test file of your own.

Is fixing line breaks the right move for your file?

If the data is going to another program that reads CSV properly, leave genuine line breaks inside values alone. Make sure those values are quoted correctly and that the file uses one consistent line ending between records. You keep the original text exactly, including multi-line addresses, notes and comments.

Replacing embedded line breaks with a space, a visible marker such as \n, or another placeholder is a lossy change. It makes the file easier to handle in line-based tools and plain-text destinations. However, you can no longer tell an original line break apart from a placeholder that happened to be in the text already, unless you choose a marker that cannot occur in the data and document it.

Flattening to plain text is usually the better choice in these cases:
• The destination does not understand quoted multi-line fields, such as many line-oriented command-line tools, simple log processors, and TSV consumers that follow the strict tab-separated convention.
• The content will be pasted into a chat, email or document where people will read it as text rather than open it as a table.
• Readability matters more than exact round-trip fidelity.

What the fix actually changes

"Line break" can mean two different things in a CSV file, and confusing them causes most failed fixes.

Record separators are the line endings between rows. RFC 4180 describes them as CRLF (a carriage return followed by a line feed). Many files instead use LF alone, and some older files use CR alone. Converting between these changes the bytes stored in the file, but not the content of any field.

Embedded line breaks are line breaks inside a field value, such as a two-line street address. Under RFC 4180, a field containing a line break, a comma or a double quote must be enclosed in double quotes. A double quote inside such a field is written as two double quotes. A compliant parser treats the embedded break as part of the value, not as the end of the record.

Neither kind of break is a display setting. Both are stored characters. When a spreadsheet shows a multi-line cell or wraps long text, that is presentation. When you replace or remove a break character, you are editing the data itself. Keep the two apart when judging whether a tool preserved your content.

Example of a valid record with an embedded break. It takes up two physical lines in the file but is one logical record with three fields:

id,name,address
1,"Ada Example","12 Main St
Apt 4"
2,"Bo Sample","9 Oak Ave"

In this example, the record separators are CRLF and the break inside the first address is a lone LF. Mixing the two is common in files exported from spreadsheets. It is valid as long as the field is quoted. Removing every CR from this file would be harmless. Removing every LF, or splitting the file on every LF, would break record 1 into pieces.

Why the output differs from what you expected

Each symptom below can have more than one cause. Treat each cause as a hypothesis until a check on your own file confirms it.

Symptom | Plausible cause | Check that distinguishes it
One record is split across several rows | Embedded line break in an unquoted field, or a reader that splits on every newline instead of parsing CSV | Look at the raw text: is the broken value wrapped in double quotes? Re-read the file with a real CSV parser and compare row counts
All data appears on a single row | File uses CR-only line endings that the reader does not recognize | Inspect the raw bytes for CR characters with no LF following them
Values end with a stray character, ^M, or an odd symbol | CRLF file read by a tool that only strips LF | Look at the last field in each row for a trailing CR
Rows merge or swallow the rest of the file | An unbalanced double quote opens a field that never closes | Search for a quote character that is not doubled inside a quoted field
Blank rows appear between records after writing | File written with an extra CR added on top of CRLF | Look for CR CR LF sequences in the raw bytes
Unexpected breaks inside text that looked like one line | Unicode line or paragraph separators (such as U+2028, U+2029 or U+0085) that some line-splitting functions treat as breaks | Search for those code points; they are often invisible in editors

Checks you can run

To see line endings, use GNU cat with the -A option. It shows a carriage return as ^M and the end of each line as $. The file command also usually reports whether a text file has CRLF or CR line terminators.

cat -A data.csv | head -20
file data.csv

To tell embedded breaks apart from broken structure, compare a naive per-line field count with a count from a real CSV parser. Suppose the naive count varies from line to line but the parser reports the same number of fields for every record. Then the embedded breaks are quoted correctly and the problem is the tool that reads the file. If the parser's counts vary as well, the file itself is malformed. Note that the naive count is also thrown off by commas inside quoted fields, so treat it only as a rough signal.

# Naive: counts fields per physical line
awk -F',' '{print NF}' data.csv | sort | uniq -c

# Parser-aware: counts fields per logical record
python3 - <<'EOF'
import csv
from collections import Counter
with open("data.csv", newline="", encoding="utf-8") as f:
    print(Counter(len(row) for row in csv.reader(f)))
EOF

Targeted corrections

If your own code reads or writes the file, use a CSV library rather than splitting on newlines and commas. The Python documentation says CSV files should be opened with newline=''. Without it, embedded newlines inside quoted fields will not be read correctly, and on platforms that use CRLF an extra CR can be added when writing. That extra CR is one documented source of the blank rows described above. The csv writer uses CRLF as its record terminator by default.

import csv

with open("in.csv", newline="", encoding="utf-8") as src, \
     open("out.csv", "w", newline="", encoding="utf-8") as dst:
    writer = csv.writer(dst)  # quotes fields containing breaks, commas or quotes
    for row in csv.reader(src):
        writer.writerow(row)

If the only problem is inconsistent record separators, normalize them with a CSV-aware rewrite like the one above. Avoid blanket substitutions such as deleting every CR or splitting on every LF. Those commands cannot tell record separators apart from line breaks inside fields.

An unbalanced quote has to be fixed at the source or by hand. No automatic tool can reliably guess where the field was meant to end. Find the first record where the parser's field count goes wrong and inspect the raw text just before it.

If the destination cannot handle multi-line fields, flatten them on purpose. Replace each embedded break with a space for readability, or with a distinctive marker if you need to restore the breaks later. Do this to parsed field values, not to the raw file text.

import csv

with open("in.csv", newline="", encoding="utf-8") as src, \
     open("flat.csv", "w", newline="", encoding="utf-8") as dst:
    writer = csv.writer(dst)
    for row in csv.reader(src):
        writer.writerow([v.replace("\r\n", " ").replace("\n", " ").replace("\r", " ") for v in row])

Converting CSV to TSV

Converting to TSV is where line break problems most often turn into data loss. The common tab-separated convention assumes that fields contain no tabs, has no quoting mechanism, and treats every line as one record. A quoted multi-line CSV field therefore has no direct equivalent in strict TSV. Some tools write quoted TSV anyway, but a reader that expects strict TSV will split those records.

Before converting, decide how embedded line breaks and tabs will be represented. Common choices are replacing them with spaces, or escaping them as visible sequences such as \n and \t. Use the same rule everywhere and make sure the receiving tool expects it. Running the parser-aware field count on the output is a quick way to confirm that the record count did not change.

Will the result stay readable after copying or sharing?

Copy and paste is where quoted multi-line fields are least predictable. Whether pasted CSV text is parsed as rows and columns, kept as one block, or split at every line break depends on the destination. It can also depend on how the paste is performed. One successful paste into one application does not show that others will behave the same way, so test with a short sample containing at least one multi-line field.

Search and editing work on the stored characters. A value containing an embedded break may not match a search for the same words joined by a space. Line-oriented tools such as grep will see only part of the value on each line. Flattening helps in both cases, at the cost described earlier.

Accessibility also depends on the destination. When a CSV is opened as a proper table, assistive technology can announce rows and columns, and an embedded break is simply part of a cell. When the raw text is shared instead, a listener hears quotes, commas and fragments of records out of context. No scoped test with particular screen readers was available for this article. If the data is meant for people to read rather than for import, a short plain-text summary or a properly built table in the destination format is usually clearer than raw CSV.

Bottom line

Check before you change anything. Inspect the line endings and compare naive and parser-aware field counts to learn whether the file is malformed or the reader is at fault. Keep correctly quoted embedded breaks when the data stays in CSV-aware tools. Flatten them deliberately, at the field level, when the destination is strict TSV, a line-based tool or plain text meant for people. Behavior in specific applications has not been verified here, so confirm any import or paste path with a small sample file before you rely on it.