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)