Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Databases and Redis

NULL values turn into empty text when Python writes a CSV for PostgreSQL

Your error

Rows that were NULL in the database come back as empty strings after the CSV is loaded again2 more lines it can show

Fix it fast

Most common cause, 1 of 3

csv.writer writes None and '' the same way

On Python 3.12 or newer, write with QUOTE_NOTNULL: every value that is not None gets quotes, and None stays an unquoted empty field.

Fix
import csv
with open("export.csv", "w", newline="") as f:
    w = csv.writer(f, quoting=csv.QUOTE_NOTNULL)   # Python 3.12+
    w.writerows(rows)

# Python 3.11 and older
rows = [[r"\N" if v is None else v for v in row] for row in rows]
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

Python's csv.writer writes None as an empty field, and pandas to_csv writes missing values as na_rep, which defaults to an empty string. An empty string looks identical, so NULLs are lost or invented on import. On Python 3.12+ write with quoting=csv.QUOTE_NOTNULL; with pandas, set na_rep='\N' and load with NULL '\N'. Applies to pandas 2.x-3.1 and PostgreSQL COPY.

  • Applies to Python 3.12 to 3.15 (csv.QUOTE_NOTNULL), pandas 3.1.1, PostgreSQL 15 to 19 COPY ... (FORMAT csv)
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

Look at the raw lines for one row that has a NULL and one that has an empty string. If both show as two commas side by side, the writer flattened them; if you see \N but the table holds the text \N, the loader was not told about the marker.

Run this first
head -n 5 export.csv

Then find the line you see in this list and open its fix:

  1. 1csv.writer writes None and '' the same wayBoth values appear as ,, in the file, and the export was made with csv.writer and the default quoting
  2. 2pandas to_csv writes NaN, None and NA as na_rep, which is emptyThe export came from DataFrame.to_csv() with no na_rep argument
  3. 3COPY reads the file with its own NULL ruleThe table shows the literal text \N, or an integer column fails on "\N", or quoted empty fields arrive as ''

What does the error look like?

  • Rows that were NULL in the database come back as empty strings after the CSV is loaded again
  • Empty strings load as NULL, or a NOT NULL column rejects them
  • The file shows ,, for both None and ''

Cause 1 of 3

csv.writer writes None and '' the same way

You seeBoth values appear as ,, in the file, and the export was made with csv.writer and the default quoting

Check

A NULL turns into an empty string because the csv module writes None as the empty string by design, and with the default QUOTE_MINIMAL an empty string is written the same way. Nothing in the file then says which field was NULL. PostgreSQL's CSV mode can only tell them apart by quoting: an unquoted empty field is NULL, a quoted "" is an empty string.

Check
import csv, io
buf = io.StringIO()
csv.writer(buf).writerow([1, None, ""])
print(repr(buf.getvalue()))   # '1,,\r\n' -> None and "" look alike

Fix

On Python 3.12 or newer, write with QUOTE_NOTNULL: every value that is not None gets quotes, and None stays an unquoted empty field. On older Python, replace None with \N before writing and load with NULL '\N'.

Fix
import csv
with open("export.csv", "w", newline="") as f:
    w = csv.writer(f, quoting=csv.QUOTE_NOTNULL)   # Python 3.12+
    w.writerows(rows)

# Python 3.11 and older
rows = [[r"\N" if v is None else v for v in row] for row in rows]

Verify

A row holding 1, None and '' is now written as "1",,"" rather than 1,, so the loader can tell the two apart.

Verify
buf = io.StringIO()
csv.writer(buf, quoting=csv.QUOTE_NOTNULL).writerow([1, None, ""])
print(repr(buf.getvalue()))

Confirmed by docs.python.org

Did this fix it?

Cause 2 of 3

pandas to_csv writes NaN, None and NA as na_rep, which is empty

You seeThe export came from DataFrame.to_csv() with no na_rep argument

Check

pandas loses the NULLs because to_csv writes every missing value with na_rep, and na_rep defaults to an empty string. Since pandas 3.0 the default str dtype marks missing text as NaN too, and to_csv writes it with na_rep like any other missing value.

Check
import sys
print(df.isna().sum())          # how many missing values each column holds
df.head(3).to_csv(sys.stdout, index=False)

Fix

Give missing values a marker that cannot be real data, and use the same marker when you load the file.

Fix
df.to_csv("export.csv", index=False, na_rep=r"\N")

Verify

The marker appears in the file as often as isna() counted missing values.

Verify
grep -o '\\N' export.csv | wc -l

Confirmed by pandas.pydata.org

Did this fix it?

Cause 3 of 3

COPY reads the file with its own NULL rule

You seeThe table shows the literal text \N, or an integer column fails on "\N", or quoted empty fields arrive as ''

Check

Even a correct file loses NULLs if COPY is not told the marker. In CSV format PostgreSQL's NULL string defaults to an unquoted empty field, so \N is loaded as two characters of text, and a quoted "" stays an empty string unless FORCE_NULL is set for that column.

Check
SELECT count(*) FILTER (WHERE email IS NULL) AS nulls, count(*) FILTER (WHERE email = '') AS empties FROM users;

Fix

Name the marker in the COPY options. psql's \copy passes them to COPY and reads the file from your own machine.

Fix
\copy users FROM 'export.csv' WITH (FORMAT csv, HEADER true, NULL '\N')

-- file from csv.QUOTE_NOTNULL: keep the default NULL '' and quotes do the rest
\copy users FROM 'export.csv' WITH (FORMAT csv, HEADER true)

Verify

The NULL count in the table matches the number of markers or unquoted empty fields in the file.

Verify
SELECT count(*) FROM users WHERE email IS NULL;

Confirmed by postgresql.org

Did this fix it?

How do I stop it coming back?

  • Pick one NULL convention per pipeline (QUOTE_NOTNULL or a \N marker), write it in the export function, and pass the same value to every COPY that reads the file.
  • Add a round-trip test: export a fixture row holding both None and '', load it into a scratch table, and assert one IS NULL and one = ''.
  • When the data already lives in PostgreSQL, let COPY ... TO write the CSV; it marks NULL and empty strings apart on its own.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: stegnor.com, Menulo, ShopGo.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.