Skip to content

Commit

Permalink
fix(python): Raise a proper python typed exception when the CSV write…
Browse files Browse the repository at this point in the history
…r tries to write to an non existent folder (pola-rs#12919)
  • Loading branch information
Yerachmiel-Feltzman authored Dec 6, 2023
1 parent 026377c commit 23cfaf1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
3 changes: 2 additions & 1 deletion py-polars/src/dataframe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
14 changes: 12 additions & 2 deletions py-polars/tests/unit/io/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -19,8 +20,6 @@
from polars.utils.various import normalize_filepath

if TYPE_CHECKING:
from pathlib import Path

from polars.type_aliases import TimeUnit


Expand Down Expand Up @@ -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)

0 comments on commit 23cfaf1

Please sign in to comment.