From 23cfaf1acba1fa2a4e0f8cec806a0632f3f680b8 Mon Sep 17 00:00:00 2001 From: Yerachmiel Feltzman <69943828+Yerachmiel-Feltzman@users.noreply.github.com> Date: Wed, 6 Dec 2023 23:46:54 +0200 Subject: [PATCH] fix(python): Raise a proper python typed exception when the CSV writer tries to write to an non existent folder (#12919) --- py-polars/src/dataframe.rs | 3 ++- py-polars/tests/unit/io/test_csv.py | 14 ++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/py-polars/src/dataframe.rs b/py-polars/src/dataframe.rs index dc0359d9bfad..3d307568b5f9 100644 --- a/py-polars/src/dataframe.rs +++ b/py-polars/src/dataframe.rs @@ -617,7 +617,8 @@ impl PyDataFrame { if let Ok(s) = py_f.extract::<&str>(py) { py.allow_threads(|| { - let f = std::fs::File::create(s).unwrap(); + let f = std::fs::File::create(s).map_err(PolarsError::Io)?; + // No need for a buffered writer, because the csv writer does internal buffering. CsvWriter::new(f) .include_bom(include_bom) diff --git a/py-polars/tests/unit/io/test_csv.py b/py-polars/tests/unit/io/test_csv.py index d67f0dd2980a..5494874f17cf 100644 --- a/py-polars/tests/unit/io/test_csv.py +++ b/py-polars/tests/unit/io/test_csv.py @@ -6,6 +6,7 @@ import textwrap import zlib from datetime import date, datetime, time, timedelta, timezone +from pathlib import Path from typing import TYPE_CHECKING, TypedDict import numpy as np @@ -19,8 +20,6 @@ from polars.utils.various import normalize_filepath if TYPE_CHECKING: - from pathlib import Path - from polars.type_aliases import TimeUnit @@ -1710,3 +1709,14 @@ def test_csv_no_new_line_last() -> None: "a": [1, 2, 3], "b": [1.0, 2.0, 2.1], } + + +def test_write_csv_no_location_raise_io_exception() -> None: + df = pl.DataFrame({"a": [1]}) + non_existing_path = Path("non", "existing", "path", "file.csv") + if non_existing_path.exists(): + pytest.fail( + "Testing on a non existing path failed because the path does exist." + ) + with pytest.raises(FileNotFoundError): + df.write_csv(non_existing_path)