Skip to content

Write to comma-separated values (CSV) file

Description

Write to comma-separated values (CSV) file

Usage

<DataFrame>$write_csv(
  file,
  ...,
  include_bom = FALSE,
  include_header = TRUE,
  separator = ",",
  line_terminator = "\n",
  quote = "\"",
  batch_size = 1024,
  datetime_format = NULL,
  date_format = NULL,
  time_format = NULL,
  float_precision = NULL,
  null_values = "",
  quote_style = "necessary"
)

Arguments

file File path to which the result should be written.
Ignored.
include_bom Whether to include UTF-8 BOM (byte order mark) in the CSV output.
include_header Whether to include header in the CSV output.
separator Separate CSV fields with this symbol.
line_terminator String used to end each row.
quote Byte to use as quoting character.
batch_size Number of rows that will be processed per thread.
datetime_format A format string, with the specifiers defined by the chrono Rust crate. If no format specified, the default fractional-second precision is inferred from the maximum timeunit found in the frame’s Datetime cols (if any).
date_format A format string, with the specifiers defined by the chrono Rust crate.
time_format A format string, with the specifiers defined by the chrono Rust crate.
float_precision Number of decimal places to write, applied to both Float32 and Float64 datatypes.
null_values A string representing null values (defaulting to the empty string).
quote_style Determines the quoting strategy used.
  • “necessary” (default): This puts quotes around fields only when necessary. They are necessary when fields contain a quote, delimiter or record terminator. Quotes are also necessary when writing an empty record (which is indistinguishable from a record with one empty field). This is the default.
  • “always”: This puts quotes around every field.
  • “non_numeric”: This puts quotes around all fields that are non-numeric. Namely, when writing a field that does not parse as a valid float or integer, then quotes will be used even if they aren’t strictly necessary.
  • “never”: This never puts quotes around fields, even if that results in invalid CSV data (e.g. by not quoting strings containing the separator).

Value

Invisibly returns the input DataFrame.

Examples

library(polars)

dat = pl$DataFrame(mtcars)

destination = tempfile(fileext = ".csv")
dat$select(pl$col("drat", "mpg"))$write_csv(destination)

pl$read_csv(destination)
#> shape: (32, 2)
#> ┌──────┬──────┐
#> │ drat ┆ mpg  │
#> │ ---  ┆ ---  │
#> │ f64  ┆ f64  │
#> ╞══════╪══════╡
#> │ 3.9  ┆ 21.0 │
#> │ 3.9  ┆ 21.0 │
#> │ 3.85 ┆ 22.8 │
#> │ 3.08 ┆ 21.4 │
#> │ 3.15 ┆ 18.7 │
#> │ …    ┆ …    │
#> │ 3.77 ┆ 30.4 │
#> │ 4.22 ┆ 15.8 │
#> │ 3.62 ┆ 19.7 │
#> │ 3.54 ┆ 15.0 │
#> │ 4.11 ┆ 21.4 │
#> └──────┴──────┘