tables.rs
743 B · rust · 27 lines
1use std::fs;2use std::path::Path;34pub fn write_csv(path: &Path, header: &[&str], rows: &[Vec<String>]) {5 let mut out = header.join(",");6 out.push('\n');7 for row in rows {8 let fields: Vec<String> = row.iter().map(|field| quote(field)).collect();9 out.push_str(&fields.join(","));10 out.push('\n');11 }12 fs::write(path, out).expect("the table is writable");13}1415pub fn write_lines(path: &Path, lines: &[String]) {16 let mut out = lines.join("\n");17 out.push('\n');18 fs::write(path, out).expect("the page is writable");19}2021fn quote(field: &str) -> String {22 if field.contains([',', '"', '\n']) {23 format!("\"{}\"", field.replace('"', "\"\""))24 } else {25 field.to_string()26 }27}