Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Polars · Module

df.write_csv

Serializes a DataFrame to CSV text or writes it to a path or writable file-like object. Options cover compression, headers, delimiters, formatting, quoting, and storage access.

How it works

The method serializes a DataFrame as CSV. Omit file to receive the serialized text, or pass a path or writable file-like object to write it; keyword options control compression, headers, separators, formatting, quoting, and related output behavior.

Syntax

DataFrame.write_csv(file: str | Path | IO[str] | IO[bytes] | None = None, *, include_bom: bool = False, compression: Literal['uncompressed', 'gzip', 'zstd'] = 'uncompressed', compression_level: int | None = None, check_extension: bool = True, include_header: bool = True, separator: str = ',', line_terminator: str = '\n', quote_char: str = '"', batch_size: int = 1024, datetime_format: str | None = None, date_format: str | None = None, time_format: str | None = None, float_scientific: bool | None = None, float_precision: int | None = None, decimal_comma: bool = False, null_value: str | None = None, quote_style: CsvQuoteStyle | None = None, storage_options: StorageOptionsDict | None = None, credential_provider: CredentialProviderFunction | Literal['auto'] | None = 'auto') -> str | None

Parameters

NameTypeDescription
filestr | Path | IO[str] | IO[bytes] | NonePath or writable text/byte file-like object; None returns the CSV as a string.
include_bomboolWhether to include a UTF-8 BOM.
compressionLiteral['uncompressed', 'gzip', 'zstd']Compression mode.
compression_levelint | NoneCompression level, when applicable.
check_extensionboolWhether to validate the filename extension against compression.
include_headerboolWhether to write a header row.
separatorstrField separator.
line_terminatorstrRow terminator.
quote_charstrCharacter used for quoting.
batch_sizeintRows processed per thread.
datetime_formatstr | NoneDatetime formatting string.
date_formatstr | NoneDate formatting string.

Returns

str | None

Key points

  • Use write_csv to serialize a DataFrame in CSV format.
  • The destination may be a path, text or byte stream, or None.
  • Supported compression modes are uncompressed, gzip, and zstd.
  • Headers are included by default and can be disabled.
  • Batch size sets how many rows each thread processes.
  • float_precision sets the number of decimal places written for floating-point values.
  • quote_style determines the CSV quoting strategy.

Common mistakes

  • Leaving file as None returns a string rather than writing a file.
  • With extension checking enabled, ensure the target filename matches the selected compression format.

Example: Return or write CSV

import polars as pl

frame = pl.DataFrame({"name": ["Ada", "Linus"], "score": [10, 20]})
csv_text = frame.write_csv()
print(csv_text)
frame.write_csv("scores.csv", include_header=True)

Calling without a file returns CSV text; providing a path writes the CSV there.

When to use it

Generate CSV text

Need CSV data in memory for an API response or downstream string processing.

Write tabular data

Export a DataFrame to a local or remote destination.

Compress CSV output

Reduce output size or produce compressed interchange files.

Customize serialization

Match a consumer's delimiter, null marker, date format, or quoting rules.

Interview questions

QWhat does write_csv return?

It converts the DataFrame to CSV. With file omitted or set to None, it returns a string; with a path or writable file-like object, it writes the output and returns None.

Follow-up: How would you produce compressed output? Pass compression="gzip" or compression="zstd", and optionally set compression_level.

QWhich options control CSV representation?

include_header controls whether column names are emitted, separator chooses the field delimiter, and line_terminator controls the row ending. quote_char selects the quoting character.

Follow-up: How can numeric output be controlled? Use float_precision, float_scientific, or decimal_comma as appropriate.

QWhat performance and storage-related parameters are available?

batch_size specifies the number of rows processed per thread. The method also accepts storage_options and a credential_provider for storage access.

Follow-up: What should be checked when writing compressed output to a path? Keep check_extension aligned with the compression setting and filename.

  • polars.read_csv
  • polars.DataFrame.write_parquet
  • polars.DataFrame.write_clipboard
  • polars.io.CsvQuoteStyle

Source: Polars.DataFrame.Write CSV. Checked 2026-10-15.