Skipping the first raw (row 0) in reading a file

#1

I’m trying read/write a file, with the below code, the file is create correctly, and is read correctly as well.
But in reading, I want to skip reading the header (i.e. the first row of the file, the line 0 of buffered.lines())

use std::fs::File;
use std::io::{Write, BufReader, BufRead};
use std::io;

fn main() {
    run();
}

fn run() -> Result<(), io::Error> {
    let path = "lines.txt";

    let mut output = File::create(path)?;
    write!(output, "year,GDP,passengars
2011,6.2,26.3
2012,6.5,26.65
2013,5.48,25.03
2014,6.54,26.01
2015,7.18,27.9
2016,7.93,30.47")?;

    let input = File::open(path)?;
    let buffered = BufReader::new(input);

    for line in buffered.lines() {   // I need to skip the first line of the file
        let record = line?;
        let data: Vec<&str> = record.split(",").collect();
        println!("{:#?}", data);
    }

    Ok(())
}
0 Likes

#2
for line in buffered.lines().skip(1)
1 Like

#3

row

0 Likes

#4

corrected, thanks :zipper_mouth_face:

0 Likes

#5

Thanks, what if I want to read the first row only?

0 Likes

#6

Just call .next() on the iterator after you first create it to get the first row. Then after that you can loop on the iterator to parse the rest of its contents. Here’s a quick example of what I mean:

fn run() -> Result<(), io::Error> {
    let path = "lines.txt";

    let mut output = File::create(path)?;
    write!(output, "year,GDP,passengars
2011,6.2,26.3
2012,6.5,26.65
2013,5.48,25.03
2014,6.54,26.01
2015,7.18,27.9
2016,7.93,30.47")?;

    let input = File::open(path)?;
    let buffered = BufReader::new(input);
    
    let mut lines_iter = buffered.lines();
    
    if let Some(header) = lines_iter.next() {
        // do stuff with the header
    }

    // keep parsing the rest of the file
    for line in lines_iter {
        let record = line?;
        let data: Vec<&str> = record.split(",").collect();
        println!("{:#?}", data);
    }

    Ok(())
}
1 Like

#7

Thanks, so to have the first row after the header, I used:

    if let Some(first_row) = lines_iter.skip(1).next() {
        println!("first_row: {:#?}", first_row?);
    }
0 Likes