Skip to content

Commit

Permalink
Improve error message in FileNotFoundError (#3448)
Browse files Browse the repository at this point in the history
  • Loading branch information
ishmandoo committed May 21, 2022
1 parent 6565276 commit edc4dbd
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
21 changes: 19 additions & 2 deletions py-polars/src/file.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Credits to https://github.com/omerbenamram/pyo3-file
use crate::prelude::resolve_homedir;
use polars::io::mmap::MmapBytesReader;
use pyo3::exceptions::PyFileNotFoundError;
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyString};
Expand Down Expand Up @@ -209,7 +210,15 @@ pub fn get_either_file(py_f: PyObject, truncate: bool) -> PyResult<EitherRustPyt
let f = if truncate {
BufReader::new(File::create(str_slice)?)
} else {
BufReader::new(File::open(str_slice)?)
match File::open(str_slice) {
Ok(file) => BufReader::new(file),
Err(e) => {
return Err(PyErr::new::<PyFileNotFoundError, _>(format!(
"No such file or directory: {}",
str_slice
)))
}
}
};
Ok(EitherRustPythonFile::Rust(f))
} else {
Expand Down Expand Up @@ -239,7 +248,15 @@ pub fn get_mmap_bytes_reader<'a>(py_f: &'a PyAny) -> PyResult<Box<dyn MmapBytesR
let s = pstring.to_string();
let p = std::path::Path::new(&s);
let p = resolve_homedir(p);
let f = File::open(&p)?;
let f = match File::open(&p) {
Ok(file) => file,
Err(e) => {
return Err(PyErr::new::<PyFileNotFoundError, _>(format!(
"No such file or directory: {}",
s
)))
}
};
Ok(Box::new(f))
}
// a normal python file: with open(...) as f:.
Expand Down
12 changes: 12 additions & 0 deletions py-polars/tests/test_df.py
Original file line number Diff line number Diff line change
Expand Up @@ -842,6 +842,18 @@ def test_file_buffer() -> None:
assert "Invalid Parquet file" in str(e.value)


def test_read_missing_file() -> None:
with pytest.raises(FileNotFoundError, match="fake_parquet_file"):
pl.read_parquet("fake_parquet_file")

with pytest.raises(FileNotFoundError, match="fake_csv_file"):
pl.read_csv("fake_csv_file")

with pytest.raises(FileNotFoundError, match="fake_csv_file"):
with open("fake_csv_file", "r") as f:
pl.read_csv(f)


def test_set() -> None:
"""Setting a dataframe using indices is deprecated. We keep these tests because we only generate a warning"""
with pytest.deprecated_call():
Expand Down

0 comments on commit edc4dbd

Please sign in to comment.