How to convert a file to a tcl list?

file, list, tcl

Solution

Something like this ought to do the trick:

proc listFromFile {filename} {
    set f [open $filename r]
    set data [split [string trim [read $f]]]
    close $f
    return $data
}
set times [listFromFile time.dat]
set accs  [listFromFile acc.dat]

The `[split]` command is doing the "heavy lifting" for you here.

EDIT

If you have a single file with both columns and you want to return that data set from a function, you have a couple choices. Both involve returning a "list of lists", and then it's just a question of whether you want two lists of N elements, or N lists of two elements. For example, to get N lists of two elements:

proc readData {filename} {
    set result {}
    set f [open $filename r]
    foreach line [split [read $f] \n] {
        lappend result $line
    }
    return $result
}

Or, to get two lists of N elements:

proc readData {filename} {
    set times {}
    set accs  {}
    set f [open $filename r]
    foreach line [split [read $f] \n] {
        lappend times [lindex $line 0]
        lappend accs  [lindex $line 1]
    }
    return [list $times $accs]
}

Technically you can even just return the data as a list of 2N elements:

proc readData {filename} {
    set result {}
    set f [open $filename r]
    foreach line [split [read $f] \n] {
        lappend result [lindex $line 0] [lindex $line 1]
    }
    return $result
}

It all depends on how you plan to use the data.

Problem

I have a file named time.dat and acc.dat both of which contains a single column containing numerical values. I want to create lists from these files which contain the values in the files. Anyone knows how to do it? ``` proc ReadRecord {inFilename outFilenameT outFilenameS} { if [catch {open $inFilename r} inFileID] { puts stderr "Cannot open $inFilename for reading" } else { set outFileIDS [open $outFilenameS w] set outFileIDT [open $outFilenameT w] foreach line [split [read $inFileID] \n] { if {[llength $line] == 0} { continue } else { puts $outFileIDT [lindex $line 0] puts $outFileIDS [lindex $line 1] } } close $outFileIDT close $outFileIDS close $inFileID } }; ```

Original source