How to open and read files in Tcl

Reading a file

To open and read files in tcl, use the open and read commands. In this example, file_io.dat is our file to be read in.

set myFile_fp [open "file_io.dat"]
set myfile_data [read $myFile_fp]
set myFile_text [split $myFile_data "\n"]

The split command is necessary  to properly read files separated by newlines.

Lets say I have a file file_io.dat with the following contents

Adam English 76
Adam Maths 76
Gary English  89
Gary Maths 90

The full tcl script to read a file and print them out is demonstrated below:

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/tclsh
set myFile "file_io.dat"
set myFile_fp [open $myFile r]
set myFile_data [read $myFile_fp]
set myFile_text [split $myFile_data "\n"]
close $myFile_fp
 
foreach line $myFile_text {
    puts $line
}

Output:

Adam English 76
Adam Maths 76
Gary English  89
Gary Maths 90

Had we not split the file by newlines, the output would have been:

Adam
English
76
Adam
Maths
76
Gary
English
89
Gary
Maths
90

Finally, it is a good practice to close the file after reading the contents of a file.

close $myFile_fp