Developer & Network Tools

CSV Pitfalls and How to Avoid Them

Stop CSV files from losing zeros, mangling accents or shifting columns, with safe habits for exporting and importing.

Key takeaways

  • CSV has no single enforced standard; RFC 4180 describes a common form that not every program follows.
  • Fields containing delimiters, quotes or line breaks must be quoted, with inner quotes doubled.
  • Opening a file directly in a spreadsheet can strip leading zeros, round long numbers and turn text into dates.
  • A file carries no information about its encoding, delimiter or column types, so state them and check them.
  • Treat cells that begin with formula characters as a security risk when exporting data that users supplied.

Most CSV trouble comes from four things: commas or line breaks inside values, a wrong guess about text encoding, a different delimiter or decimal mark, and spreadsheet software that "helpfully" converts values when it opens a file. You can avoid nearly all of it by using a real CSV library, saving as UTF-8, and importing columns as text when they're identifiers.

CSV means comma-separated values. Each line is a record and commas divide the fields. It looks too simple to go wrong, which is why people write their own handling for it and get caught.

What a well-formed file looks like

id,name,note
001,"Lee, Dana","Said ""call later"""
002,Sam Ortiz,"Two lines:
second line"

This follows the usual rules. The first line is an optional header. A value containing a comma is wrapped in double quotes. A quote inside a quoted value is written twice. A quoted value may even contain a line break, so one record can span several lines.

That last point surprises people. Counting lines isn't counting records, and splitting a file on newlines, then on commas, will tear such records apart.

One awkward CSV record, piece by piece
001 1 , 2 "Lee, Dana" 3 ""call"" 4 line break 5 Identifier Looks numeric, but the zeros are part of it. 1 Delimiter Divides fields, unless it sits inside quotes. 2 Quoted field The quotes protect the comma inside the name. 3 Doubled quote Two quotes in a quoted field mean one real quote. 4 Record end Ends the record only when outside quotes. 5 001 1 , 2 "Lee, Dana" 3 ""call"" 4 line break 5 Identifier Looks numeric, but the zeros are part of it. 1 Delimiter Divides fields, unless it sits inside quotes. 2 Quoted field The quotes protect the comma inside the name. 3 Doubled quote Two quotes in a quoted field mean one real quote. 4 Record end Ends the record only when outside quotes. 5

Don't parse it by hand

Use a CSV library. Nearly every language has one, and it handles quoting, doubled quotes and embedded newlines.

In Python:

import csv
with open("people.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["id"], row["name"])

In PowerShell:

Import-Csv -Path .\people.csv -Encoding UTF8 | Select-Object id, name

Shell one-liners with cut or awk on commas are fine only when you're certain no field contains a comma or newline. That certainty rarely survives real data.

When writing, let the library quote for you. Concatenating strings with commas produces a broken file the first time someone's company name includes one.

Delimiters and decimal marks

In many regions the comma is the decimal separator, so spreadsheet programs there often expect semicolons between fields. A file made on one computer can open on another with everything crammed into column A, or with 3,14 split in two. Tab-separated files avoid some of this, since tabs are rarer in text.

Before importing, open the file in a plain text editor and look at the first few lines. Then choose the delimiter explicitly in the import dialog. When you produce files for others, say which delimiter, decimal mark and encoding you used.

Encoding: the garbled accents problem

A CSV file doesn't declare its encoding. If a UTF-8 file is read as an older Windows code page, é turns into é. The reverse produces replacement characters or errors.

Save and read as UTF-8. Some versions of Excel recognize UTF-8 reliably on double-click only when the file starts with a byte order mark, which is why many applications offer a "CSV UTF-8" export. Other tools may treat that mark as part of the first column name, so a lookup for id mysteriously fails. In Python, the utf-8-sig encoding strips it. The background is in ASCII, Unicode and UTF-8.

What spreadsheets change

Spreadsheet programs guess a type for each cell. The guesses damage data:

Original text What may happen
00123 Becomes 123
4111222233334444555 Shown in scientific notation, digits lost
1-2 or MAR1 Becomes a date
03/04/2026 Read as March or April depending on region
1E5 Becomes 100000
=A1+1 Runs as a formula

Saving the file afterward writes the damaged values back. Excel, for example, keeps only 15 significant digits in a number, so long account or tracking numbers can't be recovered once converted.

The safe route is to import instead of double-clicking: use the data import feature, set the encoding and delimiter, and mark identifier columns as text. Menu names vary by version and program. Newer releases may include settings to disable some automatic conversions. Keep the original file untouched and work on a copy.

Formula injection

If your system exports user-supplied text to CSV, someone can enter a value beginning with =, +, - or @, or with a tab or carriage return. A spreadsheet may treat it as a formula when a colleague opens the export, potentially building links that leak data or prompting dangerous actions.

Defenses include rejecting or sanitizing such input where it makes no sense, and prefixing risky text cells with an apostrophe or other agreed marker on export. This changes the data, so apply it to files meant for spreadsheets and document it. Remember legitimate values such as negative numbers. Anyone opening files from strangers should also heed spreadsheet security warnings.

A safe round trip

Moving data through CSV without damage
1 Export with a library UTF-8, a header row, proper quoting. 2 State the dialect Note delimiter, encoding, date and decimal formats. 3 Inspect as plain text Look at the first lines before importing. 4 Import with types set Mark IDs and codes as text. 5 Verify Compare row counts, totals and a few odd records. Export with a library UTF-8, a header row, proper quoting. 1 State the dialect Note delimiter, encoding, date and decimal formats. 2 Inspect as plain text Look at the first lines before importing. 3 Import with types set Mark IDs and codes as text. 4 Verify Compare row counts, totals and a few odd records. 5

Dates, blanks and headers

Write dates as 2026-12-05 and date-times as ISO 8601 with a time zone. They sort correctly and don't depend on regional order.

CSV can't distinguish an empty string from a missing value without a convention. Pick one, and watch for the literal words NULL, NA or None arriving as text.

Give every column a unique, stable header with no stray spaces. Don't add title rows, merged-cell leftovers or totals at the bottom; they become bogus records. Make sure every row has the same number of fields, and fail loudly when one doesn't.

Validate before you load

A file that parses can still be wrong. Check it before the data reaches anything important:

  • The header contains exactly the columns you expect, by name instead of position.
  • Every record has the right number of fields.
  • Required values are present, and numbers and dates parse.
  • Identifiers that should be unique are unique.
  • The record count and any totals match what the sender reported.

Reject the whole file, or set bad rows aside in a clearly named error file, but don't silently skip them. Report the line and the reason so the sender can fix the source. A regular expression search can help locate suspicious patterns in a test sample, and regular expressions for beginners explains how to write one.

Repeated imports and automation

An import that runs once can be watched. One that runs every night needs rules. Decide what identifies a record, so loading the same file twice updates rows instead of duplicating them. Check that the file has finished arriving before reading it, for instance by having the sender write to a temporary name and rename it when done.

Senders change formats without warning: a new column, a renamed header, a different date style. Matching columns by header name survives reordering, and failing loudly on a missing column beats loading blanks. Schedule such jobs with care, as described in cron jobs explained, and make sure someone hears about a failure.

Large files

Spreadsheet programs have row limits; a modern Excel worksheet holds 1,048,576 rows. A larger file may load partially, and saving would discard the rest. Read big files with a script that processes a row at a time, or load them into a database such as SQLite and query them there.

When to choose something else

CSV is good for flat tables that many tools must open. For nested records, use JSON or a line-delimited variant of it. For exchange where types matter, a database file or a typed columnar format keeps numbers and dates intact. For people who only need to read the figures, a real spreadsheet file preserves formatting.

You can convert small, non-sensitive samples with CSV to JSON and JSON to CSV to check how a parser sees them. For files full of personal data, remember that every copy is something to protect and eventually delete.

Agree on it in writing

When two organizations exchange files regularly, a half-page description saves hours. List each column with its name, type, whether it may be empty and an example value. State the encoding, delimiter, quoting rule, line ending, date format, time zone and how deletions are represented. Include a small sample file containing the awkward cases: a comma in a name, a quote, an accented letter, a leading zero and an empty field. Test your import against that sample whenever either side changes software.

Troubleshooting a bad import

If columns shift partway down, look for an unmatched quote on the first bad row or just above it. If everything lands in one column, the delimiter is wrong. If the first header won't match, suspect a byte order mark or a trailing space. If accents look wrong, reopen the original with the correct encoding; don't try to repair text that has already been saved in damaged form, because some characters may be gone.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in Developer & Network Tools →

Latest news on this topic