cs_csv/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
use csv::StringRecord;
use std::error::Error;
use std::fs::File;
/// 读取 CSV 文件的表头(假设第一行为表头)
///
/// # 参数
///
/// * `path` - CSV 文件的路径
///
/// # 返回
///
/// 返回一个 `Result<StringRecord, Box<dyn Error>>`,其中 `StringRecord` 包含 CSV 表头。
pub fn read_columns_headers(path: &str) -> Result<StringRecord, Box<dyn Error>> {
// 打开 CSV 文件
let file = File::open(path)?;
// 创建 CSV 读取器
let mut rdr = csv::Reader::from_reader(file);
// 读取 CSV 的表头(假定第一行是表头)
let headers = rdr.headers()?.clone();
// 返回 headers
Ok(headers)
}
pub fn add(left: u64, right: u64) -> u64 {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use tempfile::NamedTempFile;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
#[test]
fn test_read_columns_headers() {
// 创建一个临时 CSV 文件,写入测试数据
let mut temp_file = NamedTempFile::new().expect("创建临时文件失败");
writeln!(temp_file, "name,age,city").expect("写入测试数据失败");
writeln!(temp_file, "Alice,30,New York").expect("写入测试数据失败");
// 调用库函数
let file = "data.csv";
let headers = read_columns_headers(file);
// println!("headers, {:?}", headers);
println!("-------------------");
// let headers = read_columns_headers(temp_file.path().to_str().unwrap()).expect("读取 CSV 表头失败");
// 检查表头内容
let expected = csv::StringRecord::from(vec!["name", "age", "city"]);
// assert_eq!(headers, expected);
}
}