Skip to main content

loadtxt

Function loadtxt 

Source
pub fn loadtxt<T>(fname: &Path, options: LoadTxtOptions) -> Result<Array<T>>
where T: Clone + Default + FromStr + Zero, <T as FromStr>::Err: Debug,
Expand description

Load data from a text file

§Arguments

  • fname - Path to the text file
  • options - Loading options (use LoadTxtOptions::default() for defaults)

§Returns

A 2D Array containing the loaded data

§Examples

use numrs2::io::text::{loadtxt, LoadTxtOptions};
use std::path::Path;
use std::fs::File;
use std::io::Write;
use tempfile::NamedTempFile;

// Create a temporary test file
let mut temp_file = NamedTempFile::new().expect("Failed to create temp file");
writeln!(temp_file, "1.0 2.0 3.0").expect("Failed to write to temp file");
writeln!(temp_file, "4.0 5.0 6.0").expect("Failed to write to temp file");

// Load with default options
let array = loadtxt::<f64>(temp_file.path(), LoadTxtOptions::default()).expect("Failed to load text file");
assert_eq!(array.shape(), &[2, 3]);

// Load with custom delimiter and skip first row
let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");
writeln!(temp_file2, "header,line").expect("Failed to write to temp file");
writeln!(temp_file2, "1.0,2.0").expect("Failed to write to temp file");
writeln!(temp_file2, "3.0,4.0").expect("Failed to write to temp file");

let mut options = LoadTxtOptions::default();
options.delimiter = Some(",".to_string());
options.skiprows = 1;
let array = loadtxt::<f64>(temp_file2.path(), options).expect("Failed to load text file");
assert_eq!(array.shape(), &[2, 2]);