gpt4 book ai didi

csv - 如何附加到现有的 CSV 文件?

转载 作者:行者123 更新时间:2023-11-29 08:22:44 25 4
gpt4 key购买 nike

例如,当运行下面的代码时,每次以前的 test.csv 文件都会被新文件覆盖。如何附加到 test.csv 而不是覆盖它?

extern crate csv;

use std::error::Error;
use std::process;

fn run() -> Result<(), Box<Error>> {
let file_path = std::path::Path::new("test.csv");
let mut wtr = csv::Writer::from_path(file_path).unwrap();

wtr.write_record(&["City", "State", "Population", "Latitude", "Longitude"])?;
wtr.write_record(&["Davidsons Landing", "AK", "", "65.2419444", "-165.2716667"])?;
wtr.write_record(&["Kenai", "AK", "7610", "60.5544444", "-151.2583333"])?;
wtr.write_record(&["Oakman", "AL", "", "33.7133333", "-87.3886111"])?;

wtr.flush()?;
Ok(())
}

fn main() {
if let Err(err) = run() {
println!("{}", err);
process::exit(1);
}
}

如果文件尚不存在,追加解决方案是否有效?

最佳答案

csv crate 提供 Writer::from_writer所以你可以使用任何实现 Write 的东西.使用 File 时, this answer来自 What is the best variant for appending a new line in a text file?显示解决方案:

Using OpenOptions::append is the clearest way to append to a file

let mut file = OpenOptions::new()
.write(true)
.append(true)
.open("test.csv")
.unwrap();
let mut wtr = csv::Writer::from_writer(file);

Will the append solution work if the file does not yet exist?

只需将 create(true) 添加到 OpenOptions 即可:

let mut file = OpenOptions::new()
.write(true)
.create(true)
.append(true)
.open("test.csv")
.unwrap();
let mut wtr = csv::Writer::from_writer(file);

关于csv - 如何附加到现有的 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50519900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com