在Rust中,可以使用csv
等库来高性能读写CSV文件。
首先,需要在Cargo.toml
文件中添加依赖项:
toml
[dependencies]
csv = "1.1"
分别定义读写CSV文件函数:
- csv_file.rs
rust
use csv::ReaderBuilder;
use csv::WriterBuilder;
use std::fs::File;
pub fn read_csv_file(path: &str) -> Result<(), csv::Error> {
let file = File::open(path)?;
let mut reader = ReaderBuilder::new().from_reader(file);
for result in reader.records() {
let record = result?;
// 处理每一行的数据
println!("{:?}", record);
}
Ok(())
}
pub fn write_csv_file(path: &str, headers: Vec<String>, records: Vec<Vec<String>>) -> Result<(), csv::Error> {
let file = File::create(path)?;
let mut writer = WriterBuilder::new().from_writer(file);
writer.write_record(headers)?;
for record in records {
writer.write_record(record)?;
writer.flush()?;
}
Ok(())
}
写入数据,再读取数据示例:
rust
mod utils;
mod macros;
fn main() {
// 保存的文件路径和文件名
let path = "D://file.csv";
// 写入CSV文件头
let headers = vec_s!["number", "Name", "Age", "City"];
let mut records = vec![];
// 写入CSV文件内容
for i in 0..10 {
records.push(vec_s![i, "Alice", "30", "New York"]);
records.push(vec_s![i, "Bob", "25", "San Francisco"]);
records.push(vec_s![i, "Charlie", "22", "Los Angeles"]);
}
utils::csv_file::write_csv_file(path, headers, records).expect("Failed to write CSV file");
utils::csv_file::read_csv_file(path).expect("Failed to read CSV file");
}
vec_s!
是一个保存字符串类型的宏,该文章进行了详细讲解:Rust 宏