Data files: CSV and NumPy .npy and .npz
| Problem | Exchange tables and arrays with spreadsheets, databases and Python: delimited text that any program can read, and a binary array format that keeps types and shapes exactly, and the ZIP archive of such arrays that NumPy calls .npz |
| Devised by | Delimited text since the 1970s, standardised by Yakov Shafranovich in RFC 4180 (2005); Robert Kern and the NumPy developers (2007), the .npy format and .npz archives; Phil Katz (1989), the ZIP format, whose ZIP64 extension (2001) lifted the 4 GiB limits |
| Accuracy | Python’s csv module and NumPy read the library’s files identically, and the library reads every tested .npy dtype, byte order, memory order and format version, and every member of five .npz archives, identically (tables below) |
| Cost | |
| Read first | Nothing beyond the Preliminaries |
| API | parse_csv, format_csv, format_csv_f64, read_csv_file, write_csv_file, CsvTable (column_index, column_f64, to_f64_rows), npy_decode, npy_encode, read_npy_file, write_npy_file, NpyArray (to_f64, from_f64), NpyData, npz_decode, npz_encode, npz_encode_positional, NpzArchive (names, get, raw), read_npz_file, write_npz_file |
Overview
Scientific work moves data between programs constantly. CSV (comma-separated values) is the universal table format. Every spreadsheet, database and plotting tool reads it, and a person can read it too. Its weaknesses are that numbers become text and that fields containing commas, quotes or line breaks must be quoted. .npy is NumPy’s binary format for one array: a small text header giving the element type, the memory order and the shape, then the raw bytes. It round-trips floats exactly, loads fast, and is the easiest way to hand arrays to and from Python. .npz holds several arrays by name: a ZIP archive with one .npy member per array, stored (numpy.savez) or deflated (numpy.savez_compressed).
Where it is used
CSV and NumPy files are how numerical results leave a program.
- Spreadsheets and databases. CSV is the lingua franca for tables of measurements, experiment logs and results sent to colleagues.
- Python workflows.
.npyand.npzfiles exchange arrays with NumPy, SciPy and machine-learning tools without conversion errors. - Reproducibility. Saving inputs and outputs of a computation in a standard format lets others rerun and check it.
History
Comma-separated lists of values appear in IBM’s FORTRAN list-directed input of 1972, and the format spread with spreadsheets from VisiCalc (1979) onwards. It went unstandardised for decades, which is why programs still disagree on quoting, delimiters and line endings. Yakov Shafranovich’s RFC 4180 (2005) wrote down the common rules: fields separated by commas, records by line breaks, and fields with special characters wrapped in double quotes, with embedded quotes doubled. NumPy’s .npy format was proposed by Robert Kern in NEP 1 (2007) as a simple, documented replacement for pickling arrays. Version 2.0 (2014) allowed larger headers, and version 3.0 (2018) UTF-8 field names in structured types. numpy.savez followed in the same period, built on Python’s zipfile. The ZIP container itself is Phil Katz’s (PKZIP, 1989); the 2001 ZIP64 extension added 64-bit sizes and offsets, which NumPy asks for on every member, since it cannot know in advance how large an array will be.
The idea
CSV
The parser reads characters into fields, with a flag for whether it is inside quotes. Outside quotes, the delimiter ends a field and a line break (LF or CRLF) ends a record. Inside quotes, everything is literal except a doubled quote, which stands for one quote character, and a single quote, which closes the field. A quote in the middle of an unquoted field, or a quoted field never closed, is an error rather than a guess. The writer quotes exactly the fields that need it:
fn write_field(out: &mut String, field: &str, delimiter: char) {
if field.contains(delimiter) || field.contains('"') || field.contains('\n') || field.contains('\r') || field.starts_with(' ') || field.ends_with(' ') {
out.push('"');
out.push_str(&field.replace('"', "\"\""));
out.push('"');
} else {
out.push_str(field);
}
}
For numbers, format_csv_f64 writes Rust’s shortest representation that parses back to the same f64, so numeric tables round-trip exactly, and writes NaN as an empty field. column_f64 and to_f64_rows read empty fields back as NaN. A blank line is therefore a record with one empty field, not nothing, unlike Python’s csv module, so that one-column tables with missing values survive a round trip.
NumPy .npy
The file starts with the magic string \x93NUMPY, a major and minor version, and a little-endian header length: two bytes in version 1.0, four in 2.0 and 3.0. The header is a Python dictionary literal such as {'descr': '<f8', 'fortran_order': False, 'shape': (3, 4), }, padded with spaces so the data start on a 64-byte boundary. The descr code gives the byte order (< little, > big, | not applicable), the kind (b boolean, i signed, u unsigned, f float, c complex) and the size in bytes.
pub fn npy_decode(bytes: &[u8]) -> Result<NpyArray, ErrorsJSL> {
if bytes.len() < 10 || &bytes[..6] != b"\x93NUMPY" {
return Err(corrupt("Not a .npy file."));
}
let (header_len, offset) = match bytes[6] {
1 => (u16::from_le_bytes([bytes[8], bytes[9]]) as usize, 10),
2 | 3 if bytes.len() >= 12 => (u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize, 12),
_ => return Err(corrupt("Unsupported .npy version.")),
};
let header = std::str::from_utf8(bytes.get(offset..offset + header_len).ok_or(corrupt("Truncated .npy header."))?).map_err(|_| corrupt("Non-text .npy header."))?;
let descr_text = header_value(header, "descr")?;
let descr = descr_text.strip_prefix('\'').and_then(|s| s.split('\'').next()).ok_or(corrupt("Unsupported .npy dtype."))?;
let fortran = header_value(header, "fortran_order")?.starts_with("True");
let shape_text = header_value(header, "shape")?;
let close = shape_text.find(')').ok_or(corrupt("Malformed .npy shape."))?;
let inner = shape_text.get(1..close).filter(|_| shape_text.starts_with('(')).ok_or(corrupt("Malformed .npy shape."))?;
let shape: Vec<usize> = inner.split(',').map(str::trim).filter(|s| !s.is_empty()).map(|s| s.parse().map_err(|_| corrupt("Malformed .npy shape."))).collect::<Result<_, _>>()?;
let count = shape.iter().try_fold(1usize, |a, &b| a.checked_mul(b)).ok_or(corrupt("The .npy shape is too large."))?;
let (order, kind, size) = {
let mut chars = descr.chars();
let order = chars.next().ok_or(corrupt("Empty dtype."))?;
let kind = chars.next().ok_or(corrupt("Empty dtype."))?;
let size: usize = chars.as_str().parse().map_err(|_| corrupt("Unsupported .npy dtype."))?;
(order, kind, size)
};
let big = order == '>';
let end = count.checked_mul(size).and_then(|n| n.checked_add(offset + header_len)).ok_or(corrupt("The .npy shape is too large."))?;
let body = bytes.get(offset + header_len..end).ok_or(corrupt("Truncated .npy data."))?;
macro_rules! read {
($t:ty, $n:expr) => {
body.chunks_exact($n).map(|c| { let a: [u8; $n] = c.try_into().expect("exact"); if big { <$t>::from_be_bytes(a) } else { <$t>::from_le_bytes(a) } }).collect::<Vec<$t>>()
};
}
let data = match (kind, size) {
('b', 1) => NpyData::Bool(body.iter().map(|&b| b != 0).collect()),
('i', 1) => NpyData::I8(read!(i8, 1)),
('i', 2) => NpyData::I16(read!(i16, 2)),
('i', 4) => NpyData::I32(read!(i32, 4)),
('i', 8) => NpyData::I64(read!(i64, 8)),
('u', 1) => NpyData::U8(body.to_vec()),
('u', 2) => NpyData::U16(read!(u16, 2)),
('u', 4) => NpyData::U32(read!(u32, 4)),
('u', 8) => NpyData::U64(read!(u64, 8)),
// Half precision is widened to single, which is exact; it is written back as `<f4`.
('f', 2) => NpyData::F32(read!(u16, 2).into_iter().map(half_to_f32).collect()),
('f', 4) => NpyData::F32(read!(f32, 4)),
('f', 8) => NpyData::F64(read!(f64, 8)),
('c', 8) => NpyData::C64(read!(f32, 4).chunks_exact(2).map(|p| Complex::new(p[0], p[1])).collect()),
('c', 16) => NpyData::C128(read!(f64, 8).chunks_exact(2).map(|p| Complex::new(p[0], p[1])).collect()),
_ => return Err(corrupt("Unsupported .npy dtype.")),
};
let data = if fortran && shape.len() > 1 { to_c_order(data, &shape) } else { data };
NpyArray::new(shape, data)
}
The reader handles booleans, signed and unsigned integers of 1 to 8 bytes, 16-, 32- and 64-bit floats (half precision is widened to single, exactly, and written back as single) and 64- and 128-bit complex numbers, in either byte order and in C or Fortran order, and returns elements in C (row-major) order as an NpyData variant of the right type. to_f64 converts any real type to an ndarray of f64. The writer produces version 1.0, little-endian and C order, which every NumPy reads.
NumPy .npz
An archive is a sequence of members, each a local header, the (possibly deflated) data and, optionally, a data descriptor, followed by a central directory that lists every member again, and an end-of-central-directory record that locates the directory. Because the directory is at the end, a reader starts there: it searches backwards for the end record’s signature, reads the directory, and then jumps to each member.
- The central directory is the authority. A member’s local header can carry zeros for the sizes and the checksum when the writer could not seek back, and a data descriptor after the data then supplies them. Reading from the directory means those files need no special case.
- When a size or an offset reaches , or there are 65 535 members or more, the fixed fields hold the marker
0xFFFFFFFFand a ZIP64 extra field holds the 64-bit value; the end record is preceded by a ZIP64 end record and a locator. - Each member is a CRC-32 checked, stored or deflated
.npyfile called<name>.npy.numpy.loadshows the names without the suffix, andsaveznames positional arraysarr_0,arr_1, and so on.
An archive is also a way to attack the program that reads it, so the reader refuses what it cannot handle safely: encrypted members, compression methods other than stored and deflate, names that are absolute or contain .., a backslash or a drive letter, two members of one name, a directory that does not fit in the file, a member whose expanded size differs from the one recorded, one that expands past 64 GiB (or past the size the directory declares, which stops a decompression bomb early) and a CRC-32 mismatch. Nothing is extracted by name.
Reading and writing other programs’ files
Files written by Python’s libraries, read by this one:
Table 26.9. CSV and NumPy files written by Python and read by the library.
| file written by Python | bytes | read by the library |
|---|---|---|
| csv (Excel dialect) | 71 | 4 records, fields identical: true |
| csv (semicolons) | 65 | 4 records, fields identical: true |
| npy float64 | 224 | identical |
| npy float32 | 148 | identical |
| npy int16 | 152 | identical |
| npy uint8 3-D | 152 | identical |
| npy bool | 131 | identical |
| npy big-endian | 176 | identical |
| npy Fortran order | 224 | identical |
| npy int64 | 144 | identical |
| npy scalar | 136 | identical |
| npy version 2.0 | 168 | identical |
| npy version 3.0 | 168 | identical |
Files written by this library, read by Python’s:
Table 26.10. CSV and NumPy files written by the library and read by Python.
| file written by the library (read by) | result |
|---|---|
| CSV with quotes, delimiters and line breaks in fields (csv module) | identical: True |
| NPY, float64 (NumPy) | float64 (3, 4), identical: True |
| NPY, int32 (NumPy) | int32 (2, 3), identical: True |
| NPY, complex128 (NumPy) | complex128 (2,), identical: True |
| NPY, bool (NumPy) | bool (2,), identical: True |
Archives:
Table 26.11. `.npz` archives written by NumPy and Python and read by the library, and written by the library and read by NumPy.
| Archive | Written by | Members the library reads identically to NumPy | NumPy reads the library’s archive |
|---|---|---|---|
numpy_exotic.npz | np.savez of a big-endian >i4, a Fortran-order array and a float16 array | 3 of 3 | — |
numpy_savez_compressed.npz | np.savez_compressed: deflated | 6 of 6 | — |
numpy_savez_named.npz | np.savez(f, **arrays): stored, six dtypes and shapes including a scalar | 6 of 6 | — |
numpy_savez_positional.npz | np.savez(f, a, b, c): members arr_0, arr_1, arr_2 | 3 of 3 | — |
python_descriptors.npz | zipfile to a stream that cannot seek: a data descriptor after each deflated member | 2 of 2 | — |
library_savez.npz | the library, npz_encode(.., false) | — | yes |
library_savez_compressed.npz | the library, npz_encode(.., true) | — | yes |
library_zip64.npz | the library, npz_encode_zip64: ZIP64 records on every member and the directory | — | yes |
Algorithm
Parsing CSV. The parser reads one character at a time and is in one of two states.
- Outside quotes: a delimiter ends the current field; a line ending ends the current field and the record; a quote at the start of a field enters the quoted state; any other character is added to the field.
- Inside quotes: two quotes in a row add one quote to the field; a single quote leaves the quoted state; any other character, including a delimiter or a line ending, is added to the field.
When reading a file, a byte-order mark at the very start is removed first.
Writing CSV: for each field, if it contains the delimiter, a quote, a carriage return or a line feed, write it between quotes with every quote inside it doubled; otherwise write it as it is.
Reading an .npy file.
- Check the six-byte magic string and read the version.
- Read the length of the header: two bytes in version 1, four in later versions.
- Parse the header, a Python dictionary written as text, for the three keys
descr(the element type and byte order),fortran_orderandshape. - Check that the amount of data that follows equals the product of the shape times the element size.
- Read the elements, swapping bytes if the file’s byte order differs from the machine’s.
- If the file is in Fortran (column-major) order, transpose to C (row-major) order.
Reading an .npz archive.
- Search backwards, from the last byte, for the end-of-central-directory signature whose comment length reaches exactly the end of the file.
- If a field is
0xFFFFor0xFFFFFFFF, follow the locator just before it to the ZIP64 end record and take the member count, directory size and offset from there. - For each directory entry read the name, method, CRC-32, compressed and expanded sizes and offset, replacing a size or offset equal to
0xFFFFFFFFby the value in the ZIP64 extra field, in the order expanded size, compressed size, offset. Refuse unsafe names and repeated names. - To read a member, check its local header’s signature, skip it (its name and extra field lengths are its own), take the compressed bytes, expand them to at most the recorded size, and check the size and the CRC-32.
- Decode the result as
.npy.
Writing an .npz archive: encode each array as .npy; store it, or deflate it; write a local header (with ZIP64 sizes only if needed), the name and the data; then the central directory with the same information, and the end record, preceded by the ZIP64 end record and locator if a count, size or offset needs them.
Writing an .npy file: build the header dictionary; pad it with spaces and a final
newline so that the data begins at a multiple of 64 bytes; write the magic string, version,
header length and header; append the elements in little-endian order.
Implementation
CsvTableholds an optional header and rows ofStringfields; rows may have different lengths, andto_f64_rowschecks them.NpyArray::newchecks that the shape matches the data length; an empty shape is a scalar.
/// A parsed `.npz` archive, borrowing its bytes. Members are decoded on demand.
#[derive(Clone, Debug)]
pub struct NpzArchive<'a> {
bytes: &'a [u8],
entries: Vec<Entry>,
}
impl<'a> NpzArchive<'a> {
/// Reads the central directory of a ZIP archive, validating every member's name.
pub fn new(bytes: &'a [u8]) -> Result<Self, ErrorsJSL> {
let len = bytes.len();
if len < 22 {
return Err(bad("Not a ZIP archive."));
}
// The end-of-central-directory record: the last 22 + comment bytes.
let eocd = (len.saturating_sub(22 + U16_MAX)..=len - 22)
.rev()
.find(|&i| u32_at(bytes, i).ok() == Some(SIG_EOCD) && u16_at(bytes, i + 20).ok().is_some_and(|c| i + 22 + c as usize == len))
.ok_or_else(|| bad("Not a ZIP archive: no end-of-central-directory record."))?;
let (disk, cd_disk) = (u16_at(bytes, eocd + 4)?, u16_at(bytes, eocd + 6)?);
let mut total = u16_at(bytes, eocd + 10)? as u64;
let mut cd_size = u32_at(bytes, eocd + 12)? as u64;
let mut cd_offset = u32_at(bytes, eocd + 16)? as u64;
if total == U16_MAX as u64 || cd_size == U32_MAX || cd_offset == U32_MAX {
// ZIP64: the locator sits just before the end record and points at the ZIP64 record.
let loc = eocd.checked_sub(20).filter(|&l| u32_at(bytes, l).ok() == Some(SIG_LOCATOR64));
if let Some(loc) = loc {
let z = usize::try_from(u64_at(bytes, loc + 8)?).map_err(|_| bad("ZIP64 offset out of range."))?;
if u32_at(bytes, z)? != SIG_EOCD64 {
return Err(bad("Corrupt ZIP64 end-of-central-directory record."));
}
total = u64_at(bytes, z + 32)?;
cd_size = u64_at(bytes, z + 40)?;
cd_offset = u64_at(bytes, z + 48)?;
}
} else if disk != 0 || cd_disk != 0 {
return Err(bad("Multi-volume ZIP archives are not supported."));
}
let cd_start = usize::try_from(cd_offset).map_err(|_| bad("ZIP offset out of range."))?;
let cd_end = cd_offset.checked_add(cd_size).and_then(|e| usize::try_from(e).ok()).filter(|&e| e <= len).ok_or_else(|| bad("The central directory lies outside the archive."))?;
if total > (cd_end.saturating_sub(cd_start) / 46) as u64 {
return Err(bad("The central directory is smaller than its member count."));
}
let mut entries = Vec::with_capacity(total as usize);
let mut seen = HashSet::new();
let mut p = cd_start;
for _ in 0..total {
if u32_at(bytes, p)? != SIG_CENTRAL || p + 46 > cd_end {
return Err(bad("Corrupt ZIP central directory."));
}
let flags = u16_at(bytes, p + 8)?;
let method = u16_at(bytes, p + 10)?;
let crc = u32_at(bytes, p + 16)?;
let (mut compressed, mut size) = (u32_at(bytes, p + 20)? as u64, u32_at(bytes, p + 24)? as u64);
let (nlen, elen, clen) = (u16_at(bytes, p + 28)? as usize, u16_at(bytes, p + 30)? as usize, u16_at(bytes, p + 32)? as usize);
let mut offset = u32_at(bytes, p + 42)? as u64;
let name_end = p + 46 + nlen;
let extra_end = name_end + elen;
if extra_end + clen > cd_end {
return Err(bad("Corrupt ZIP central directory."));
}
// The ZIP64 extra field holds, in order, those of size, compressed size and offset
// that are 0xFFFFFFFF in the fixed fields.
let extra = &bytes[name_end..extra_end];
let mut q = 0;
while q + 4 <= extra.len() {
let (id, sz) = (u16_at(extra, q)?, u16_at(extra, q + 2)? as usize);
let body = extra.get(q + 4..q + 4 + sz).ok_or_else(|| bad("Corrupt ZIP extra field."))?;
if id == 1 {
let mut r = 0;
for field in [&mut size, &mut compressed, &mut offset] {
if *field == U32_MAX {
*field = u64_at(body, r)?;
r += 8;
}
}
}
q += 4 + sz;
}
let raw = &bytes[p + 46..name_end];
let name = if flags & 0x800 != 0 { std::str::from_utf8(raw).map_err(|_| bad("A ZIP member name is not valid UTF-8."))?.to_string() } else { raw.iter().map(|&c| c as char).collect() };
p = extra_end + clen;
if flags & 0x41 != 0 {
return Err(bad("Encrypted ZIP members are not supported."));
}
if name.ends_with('/') {
continue; // a directory entry
}
if !safe_name(&name) {
return Err(bad("A ZIP member name would leave the archive (absolute path, `..`, backslash)."));
}
if !seen.insert(name.clone()) {
return Err(bad("The ZIP archive has two members with the same name."));
}
entries.push(Entry { name, method, crc, compressed, size, offset });
}
Ok(NpzArchive { bytes, entries })
}
/// The member names, with `.npy` removed as `numpy.load` does.
pub fn names(&self) -> Vec<String> {
self.entries.iter().map(|e| e.name.strip_suffix(".npy").unwrap_or(&e.name).to_string()).collect()
}
/// The number of members.
pub fn len(&self) -> usize {
self.entries.len()
}
/// Whether the archive has no members.
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// Whether a member of this name exists (with or without `.npy`).
pub fn contains(&self, name: &str) -> bool {
self.find(name).is_some()
}
fn find(&self, name: &str) -> Option<&Entry> {
self.entries.iter().find(|e| e.name == name || e.name.strip_suffix(".npy") == Some(name))
}
/// The bytes of a member, expanded and checked against its CRC-32 and size.
pub fn raw(&self, name: &str) -> Result<Vec<u8>, ErrorsJSL> {
let e = self.find(name).ok_or_else(|| bad("No such member in the archive."))?;
let off = usize::try_from(e.offset).map_err(|_| bad("ZIP offset out of range."))?;
if u32_at(self.bytes, off)? != SIG_LOCAL {
return Err(bad("Corrupt ZIP local header."));
}
let (nlen, elen) = (u16_at(self.bytes, off + 26)? as usize, u16_at(self.bytes, off + 28)? as usize);
let start = off + 30 + nlen + elen;
let end = e.compressed.checked_add(start as u64).and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("ZIP size out of range."))?;
let data = self.bytes.get(start..end).ok_or_else(|| bad("Truncated ZIP member."))?;
if e.size > MAX_MEMBER {
return Err(bad("A ZIP member is larger than the size limit."));
}
let out = match e.method {
0 => {
if e.compressed != e.size {
return Err(bad("A stored ZIP member's sizes disagree."));
}
data.to_vec()
}
8 => inflate_limited(data, e.size as usize)?,
_ => return Err(bad("Unsupported ZIP compression method (only stored and deflate).")),
};
if out.len() as u64 != e.size {
return Err(bad("A ZIP member's size differs from its directory entry."));
}
if crc32(&[&out]) != e.crc {
return Err(bad("ZIP member CRC-32 mismatch."));
}
Ok(out)
}
/// The array stored in a member (the name with or without `.npy`).
pub fn get(&self, name: &str) -> Result<NpyArray, ErrorsJSL> {
npy_decode(&self.raw(name)?)
}
}
/// Builds an `.npz` archive from named arrays (`numpy.savez`, or `numpy.savez_compressed` when
/// `compressed`): each array becomes the member `<name>.npy`. Names must be non-empty, distinct,
/// and free of `/`, `\`, `..` and a trailing `.npy`. Sizes and offsets that do not fit 32 bits get
/// ZIP64 records.
pub fn npz_encode(arrays: &[(&str, &NpyArray)], compressed: bool) -> Result<Vec<u8>, ErrorsJSL> {
encode(arrays, compressed, false)
}
NpzArchiveborrows the bytes and decodes members on demand, asnumpy.loaddoes:names,contains,raw(a member’s bytes, checked) andget(a member asNpyArray).npz_decodereads all the.npymembers at once.npz_encodetakes names and arrays; names must be distinct and free of/,\,..and a trailing.npy, so that every archive it writes is one the reader accepts.npz_encode_positionalnames arraysarr_0,arr_1, … Writing deflates with level 6 whencompressed, and falls back to stored blocks for data that do not compress.npz_encode_zip64writes the ZIP64 records on every member and on the directory, as a test of readers: a file of that kind is what an archive with a member beyond 4 GiB looks like. The sizes are 64-bit throughout, but memory, not the format, limits the arrays: a member is built in memory.
In practice
//! CSV tables and NumPy .npy arrays.
use lib_jsl_file_io::{NpyArray, NpyData, format_csv, format_csv_f64, npy_decode, npy_encode, parse_csv};
use ndarray::array;
fn main() {
let text = "city,population,note\nParis,2102650,\"capital, France\"\n\"Saint-Étienne\",172718,\"say \"\"Sainté\"\"\"\n";
let table = parse_csv(text, ',', true).unwrap();
println!("header {:?}", table.header);
for row in &table.rows {
println!(" {row:?}");
}
let population = table.column_f64(table.column_index("population").unwrap()).unwrap();
println!("total population {}", population.iter().sum::<f64>());
print!("written back:\n{}", format_csv(&table, ';'));
print!("numbers (NaN as an empty field):\n{}", format_csv_f64(Some(&["x", "y"]), &[vec![0.1, 1e-300], vec![f64::NAN, -2.5]], ','));
// .npy arrays carry their element type and shape.
let a = array![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]].into_dyn();
let bytes = npy_encode(&NpyArray::from_f64(&a)).unwrap();
println!(".npy: {} bytes, header {:?}", bytes.len(), String::from_utf8_lossy(&bytes[10..60]).trim_end());
let back = npy_decode(&bytes).unwrap();
println!("shape {:?}, identical: {}", back.shape, back.to_f64().unwrap() == a);
let counts = NpyArray::new(vec![2, 2], NpyData::U16(vec![1, 2, 3, 4])).unwrap();
println!("uint16 array as f64: {:?}", npy_decode(&npy_encode(&counts).unwrap()).unwrap().to_f64().unwrap().into_raw_vec_and_offset().0);
}
header Some(["city", "population", "note"])
["Paris", "2102650", "capital, France"]
["Saint-Étienne", "172718", "say \"Sainté\""]
total population 2275368
written back:
city;population;note
Paris;2102650;capital, France
Saint-Étienne;172718;"say ""Sainté"""
numbers (NaN as an empty field):
x,y
0.1,1e-300
,-2.5
.npy: 176 bytes, header "{'descr': '<f8', 'fortran_order': False, 'shape':"
shape [2, 3], identical: true
uint16 array as f64: [1.0, 2.0, 3.0, 4.0]
Writing back with semicolons quotes only the field containing quotes. Its comma no longer needs protecting.
Strengths
- RFC 4180 CSV with any delimiter, exact numeric round trips, and strict errors on malformed quoting.
.npyreading for the common numeric dtypes in any byte order, memory order and format version, checked against NumPy.
Weaknesses
- No type inference, comment lines or dialect detection for CSV, and the whole file is read into memory.
- No structured (record) dtypes, strings or memory mapping. Half-precision arrays are widened to single on reading, so they are written back as single.
- Archives are read and written in memory, whole; members are decoded one at a time, but a member’s bytes are all expanded together. ZIP archives of several volumes, encrypted members, and compression methods other than stored and deflate are refused.
Exercises
- Write the CSV state machine as a table of (state, character) transitions, and check how it handles
"a""b",c. - Show that writing with the shortest round-trip representation and parsing it back gives exactly .
- Work out the header padding of a version 1.0
.npyfile for a(3, 4)float64 array. - Convert a Fortran-order index of an array of shape to its C-order position.
- Why does NumPy put the data on a 64-byte boundary?
- Why does a ZIP reader start at the end of the file, and why does it read sizes from the central directory instead of the local headers?
- A deflated ZIP member declares an expanded size of 100 bytes, and its data expand to a gigabyte. How does the reader stop this, and why before the CRC check?
Hints and answers
- The states are: field start, in unquoted field, in quoted field, quote seen inside a quoted field. In
"a""b",cthe first quote opens a quoted field, the doubled quote yields a literal", the next quote closes the field, and the comma ends it, giving fieldsa"bandc. - The shortest round-trip representation is the shortest decimal string that parses back to the same double; by definition parsing it recovers exactly.
- The header string for shape
(3, 4)is{'descr': '<f8', 'fortran_order': False, 'shape': (3, 4), }, 59 characters. The preamble is 10 bytes, plus the newline: 70 bytes, padded with spaces to 128, so the header length field is 118. - In Fortran order the element is at offset ; in C order it is at .
- A 64-byte boundary matches the cache-line size and the width of AVX-512 vectors, so the array data can be memory-mapped and used with aligned loads.
- The end record is the only part of the file whose position is known from the end, and it points at the directory, which points at every member: the writer need not know sizes in advance, and can append members and then the directory. The local header of a member written to a stream that cannot seek holds zeros for the sizes and CRC, because they were not known when it was written; the true values follow the data in a descriptor, and are repeated in the directory.
- Inflation is given the declared size as its limit and fails as soon as the output would exceed it, so memory use is bounded by what the (untrusted) directory declares, and that is itself bounded at 64 GiB. The CRC can only be computed on a complete output, which is what must not be allowed to grow without limit.
Further reading
- Y. Shafranovich, “Common format and MIME type for comma-separated values (CSV) files”, RFC 4180, 2005.
- R. Kern, “A simple file format for NumPy arrays”, NumPy Enhancement Proposal 1, 2007.
- PKWARE Inc., ZIP File Format Specification (APPNOTE.TXT), version 6.3.10 (2022): the end-of-central-directory record, central directory and ZIP64 extensions.
- NumPy documentation,
numpy.savez,numpy.savez_compressedandnumpy.load. - C. R. Harris et al., “Array programming with NumPy”, Nature 585 (2020) 357–362.