Character-Separated Values

Read & Write

Reading a CSV file should look familiar:

df = pl.read_csv("path.csv")
use polars::prelude::*;

let df = CsvReader::from_path("path.csv").unwrap().finish().unwrap();

CSV files come in many different flavors, so make sure to check the read_csv() API.

Writing to a CSV file can be done with the write_csv() method.

df = pl.DataFrame({"foo": [1, 2, 3], "bar": [None, "bak", "baz"]})
use polars::prelude::*;

let mut df = df!(
    "foo" => &[1, 2, 3],
    "bar" => &[None, Some("bak"), Some("baz")],

let mut file = std::fs::File::create("path.csv").unwrap();
CsvWriter::new(&mut file).finish(&mut df).unwrap();


Polars allows you to scan a CSV input. Scanning delays the actual parsing of the file and instead returns a lazy computation holder called a LazyFrame.

df = pl.scan_csv("path.csv")
use polars::prelude::*;

let df = LazyCsvReader::new("./test.csv").finish().unwrap();

If you want to know why this is desirable, you can read more about those Polars optimizations here.

The following video shows how to efficiently load CSV files with Polars and how the built-in query optimization makes this much faster.