问题描述
我正在尝试解析CSV文件,如果某个字段匹配,请使用不同的值更新某个字段,但是我不确定如何执行此操作.
I am trying to parse a CSV file and if a certain field matches, update a certain field with a different value, but I'm not sure on how to do this.
我的代码:
extern crate csv;
use std::error::Error;
fn run(file: &str, output: &str) -> Result<(), Box<Error>> {
let mut rdr = csv::Reader::from_path(file)?;
let mut wtr = csv::Writer::from_path(output)?;
wtr.write_record(rdr.byte_headers()?);
for result in rdr.byte_records() {
let mut record = result?;
if &record[0] == "05V".as_bytes() && &record[4] == "4".as_bytes() {
// let record[4] = "2"; -> Not sure how to update the field
}
wtr.write_byte_record(&record);
}
Ok(())
}
如果记录符合条件,如何更新该字段?
How can I update the field if the record matches the conditions?
推荐答案
您不要. ByteRecord
(以及扩展名为StringRecord
)存储该字段中的所有数据都紧紧包装在Vec<u8>
中.您无法轻松访问此Vec
进行修改,并且当前公开的突变方法过于粗糙,无法在这种情况下使用.您可以从记录的末尾删除字段或清除整个内容,但不能替换一个字段.
You don't. A ByteRecord
(and a StringRecord
by extension) store all of the field's data in a single tightly-packed Vec<u8>
. You cannot easily access this Vec
to modify it and the currently exposed mutation methods are too coarse to be useful in this case. You could remove fields from the end of the record or clear the entire thing, but not replace one field.
相反,您可以在需要时创建一个全新的ByteRecord
并将其输出:
Instead, you can create a brand new ByteRecord
when needed and output that:
for result in rdr.byte_records() {
let input_record = result?;
let output_record = if &input_record[0] == b"05V" && &input_record[4] == b"4" {
input_record
.into_iter()
.enumerate()
.map(|(i, v)| if i == 4 { b"2" } else { v })
.collect()
} else {
input_record
};
wtr.write_byte_record(&output_record);
}
这篇关于如何更新csv :: ByteRecord中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!