From 3e41f6c8fbb189d97c9339e6a00ba12cdf316cd7 Mon Sep 17 00:00:00 2001 From: Jim Turner Date: Sun, 7 Dec 2025 21:56:00 -0500 Subject: [PATCH 1/2] Add create_npy_npy convenience function --- src/lib.rs | 4 ++-- src/npy/mod.rs | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) 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..e5407f9 100644 --- a/src/npy/mod.rs +++ b/src/npy/mod.rs @@ -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 From 82a855e85ef4b283b72848a79ac7ab1142936e30 Mon Sep 17 00:00:00 2001 From: Jim Turner Date: Sun, 7 Dec 2025 21:56:10 -0500 Subject: [PATCH 2/2] Remove unnecessary fully qualified path --- src/npy/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/npy/mod.rs b/src/npy/mod.rs index e5407f9..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.