You are here

Appending table data to a file in a Simile script

We recently had a query from a user who is using scripting to make several runs of the same model and wanting to append data saved from the table display to one file. (Rather than a file for each run using RunControl::SaveToFile.)

At the moment there is no command to append table data to a file. However, I have had the same requirement and wrote a Tcl scipt to do the job and I post it below. (The SimileScript comands are built as an extension to the Tcl scripting language and so Tcl is available in Simile scripts.)

Add the script to the top of your own script and after saving the table data to its own file, say temp.csv, append that file to the file you want to accumulate all the results, e.g.
fileappend temp.csv results.csv

# appends the contents of the source file to the destination file
# the destination file will be created if it doesn't exist
# the first line of the source file (assumed to be column headings)
# is copied only if the destination file is empty  or does not 
# exist (first appended file)
# # example, append one.csv and two.csv to file all.csv
# fileappend one.csv all.csv
# fileappend two.csv all.csv
proc fileappend {source destination} {
    # source and destination are file names
    # open source (read) and destination (append) files
    # (destination created if it doesn't exist)
    set s [open $source  r]
    set d [open $destination a]
    # get the destination file size (among other stats)
    file stat $destination destStats
    # read in the source data
    set data [read $s]
    # split the source data in to lines
    set lines [split $data \n]
    #copy the lines to the destination file
    set i 0
    foreach {line} $lines {
        if {$i==0} {
            # if it is the the first line (column names)
            # copy only if the destination file is empty
            if {$destStats(size) == 0} {
                puts $d $line
        } else  {
            # copy all other lines
            puts $d $line
        incr i
    # close the files
    close $s
    close $d