diff --git a/src/lib.rs b/src/lib.rs index dd0c698..5240287 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,7 +18,7 @@ //! - [`read_npy`] convenience function //! - Writing //! - [`WriteNpyExt`] extension trait -//! - [`write_npy`] convenience function +//! - [`write_npy`] and [`create_new_npy`] convenience functions //! - [`write_zeroed_npy`] to write an `.npy` file (sparse if possible) of zeroed data //! - Readonly viewing (primarily for use with memory-mapped files) //! - [`ViewNpyExt`] extension trait @@ -55,7 +55,7 @@ mod npy; mod npz; pub use crate::npy::{ - read_npy, write_npy, write_zeroed_npy, ReadDataError, ReadNpyError, ReadNpyExt, + create_new_npy, read_npy, write_npy, write_zeroed_npy, ReadDataError, ReadNpyError, ReadNpyExt, ReadableElement, ViewDataError, ViewElement, ViewMutElement, ViewMutNpyExt, ViewNpyError, ViewNpyExt, WritableElement, WriteDataError, WriteNpyError, WriteNpyExt, }; diff --git a/src/npy/mod.rs b/src/npy/mod.rs index e8b30f8..4919012 100644 --- a/src/npy/mod.rs +++ b/src/npy/mod.rs @@ -35,7 +35,7 @@ where P: AsRef, T: ReadNpyExt, { - T::read_npy(std::fs::File::open(path)?) + T::read_npy(File::open(path)?) } /// Writes an array to an `.npy` file at the specified path. @@ -65,6 +65,31 @@ where array.write_npy(BufWriter::new(File::create(path)?)) } +/// Writes an array to a new `.npy` file at the specified path; error if the file exists. +/// +/// This is a convenience function for `BufWriter::new(File::create_new(path)?)` followed by +/// [`WriteNpyExt::write_npy`]. +/// +/// # Example +/// +/// ```no_run +/// use ndarray::array; +/// use ndarray_npy::create_new_npy; +/// # use ndarray_npy::WriteNpyError; +/// +/// let arr = array![[1, 2, 3], [4, 5, 6]]; +/// create_new_npy("new_array.npy", &arr)?; +/// assert!(create_new_npy("new_array.npy", &arr).is_err()); +/// # Ok::<_, WriteNpyError>(()) +/// ``` +pub fn create_new_npy(path: P, array: &T) -> Result<(), WriteNpyError> +where + P: AsRef, + T: WriteNpyExt + ?Sized, +{ + array.write_npy(BufWriter::new(File::create_new(path)?)) +} + /// Writes an `.npy` file (sparse if possible) with bitwise-zero-filled data. /// /// The `.npy` file represents an array with element type `A` and shape