vlang

Reading all csv lines


I was able to read the first line (which is the deader in my csv file) as"

import encoding.csv

    path:="file.csv"
    //mut f := os.read_file(path) or {println(err) return}
    f := os.read_file(path)?
    c:=csv.new_reader(f)
    r:=c.read()?

    println(r)

But how can I read all the lines there?

I tried:

    path:="file.csv"
    rows := os.read_lines(path)? 
    for row in rows {
        mut c:=csv.new_reader(row)
        mut r:=c.read()?
        println(r)
    }

But I got:

V panic: encoding.csv: could not find any valid line endings
print_backtrace_skipping_top_frames is not implemented

Solution

  • Here is one solution:

    import os
    import encoding.csv
    
    fn main() {
        content := os.read_file('./file.csv') ?
        mut reader := csv.new_reader(content)
        reader.read() ? // Skip the first line
        for {
            line_data := reader.read() or {
                break
            }
            println(line_data)
        }
    }
    

    My file file.csv contains the following lines:

    a,b,c
    a1,b2,c3
    a4,b5,c6
    

    I get this result:

    ['a1', 'b2', 'c3']
    ['a4', 'b5', 'c6']