3 ms·
In the last example, the call to openoptions can be replaced with the simpler File::create(), which opens the file in write mode, creates it if it doesn't exist
by joshka 2y ago
In the last example, the call to openoptions can be replaced with the simpler File::create(), which opens the file in write mode, creates it if it doesn't exist and truncates it if it does.
The weird iteration can be replaced with Itertools with_position method and filtering on Position::Middle. The python code counts the total lines by reading the file once and then iterates the file again using the count. This would be possible in the Rust approach too and would look mostly the same.
[1]: https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.create https://doc.rust-lang.org/stable/std/fs/struct.File.html#met...
[2]: https://docs.rs/itertools/0.11.0/itertools/trait.Itertools.html#method.with_position https://docs.rs/itertools/0.11.0/itertools/trait.Itertools.h...
As with any endeavor, knowing your tools helps most tasks. This is what the example looks like with full error handling and a fairly succinct yet fast approach.
use std::{
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
time::Instant
};
use color_eyre::{eyre::WrapErr, Result};
use itertools::{Itertools, Position};
fn main() -> Result<()> {
color_eyre::install()?;
let start = Instant::now();
let path = "foo/bar/baz.txt";
let tempfile = format!("{path}.tmp");
let input = File::open(path).wrap_err(format!("Failed to open file: {path}"))?;
let output = File::create(tempfile).wrap_err("Failed to create output file: {tempfile}")?;
let reader = BufReader::new(input);
let mut writer = BufWriter::new(output);
for (_, line) in reader
.lines()
.with_position()
.filter(|(position, _)| *position == Position::Middle)
{
let line = line.wrap_err("Failed to read line")?;
writeln!(writer, "{line}").wrap_err("Failed to write line")?;
}
println!("Elapsed: {:?}", start.elapsed());
Ok(())
}
As a Rust dev, I find that marginally easier to grok than the python code, probably due mainly to familiarity. But I can see why the python code would be more easier for a python dev.
My rust specific dev experience is ~18 months. I presume the OP's experience in Python is probably equal or more than this.