简体   繁体   中英

Ignore white space after reading csv file tool command line code

I am new to tcl programming, I am reading a csv file however the rows can contain a space. But tcl splits on spaces. how to ignore that default behavior. my csv is

1,fname,lname 1
2,fname,lname 2

The split works, when I try to output [lindex ${line} 2] I was expecting lname 1 . However since tcl splits on spaces how to I overcome that issue.

foreach row $data {
    set line [split ${row} ","]
    puts [lindex ${line} 0]
}

You almost have the answer right there. When doing simple CSV reading, you first split by newline to get the records, and then split by comma to get the fields in a record.

foreach row [split $data "\n"] {
    set line [split $row ","]
    puts [lindex $line 0]
}

In the complex case (once you start having fields with embedded commas and newlines and so on) you use the csv package from Tcllib, as that handles the nuances for you. In particular csv::read2matrix is helpful.


And if you can, use a character other than comma to separate fields. Tabs are a common recommended choice; that makes tab-separated files, and that's very commonly supported and usually has trouble-free interoperation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM