Previous
Procedures 
Next
TK 
Tcl/Tk Tutorial - Create GUI using Tk with Tcl Language
File Handling in Tcl/Tk

File Handling

As in all other good languages, Tcl also can open, read and write to files. And like all other good tutorials, this tutorial also teaches how to do it. First let us see how to open a file.

open

Syntax:
open fileName ?access? ?permissions?

fileName is the name of the file. The access argument, if present, specifies the way in which the file should be accessed. It can have any of the following values:

rOpen the file for reading only; the file must already exist. This is the default value if access is not specified.
r+Open the file for both reading and writing; the file must already exist.
wOpen the file for writing only. If there is a file by that name, then delete all the contents of the file. If it doesn't exist, create a new file.
w+Open the file for reading and writing. If there is a file by that name, then delete all the contents of the file. If it doesn't exist, create a new file.
aOpen the file for writing only. If the file doesn't exist, create a new empty file. Set the initial access position to the end of the file.
a+Open the file for reading and writing. If the file doesn't exist, create a new empty file. Set the initial access position to the end of the file.
Lets see an example.

#Open the file called "jokes.txt" for writing
open "jokes.txt" w

Now we know how to open a file. Not much good, is it? To make this function useful, we need to write to the file.

puts

Syntax:
puts ?-nonewline? ?channelId? string

Use the -nonewline option only if you don't need a new line at the end of the string you write to a file. The channelID stands for the ID of the output stream that must be written to(if you don't understand what the means, don't worry. You will get it latter.) string is the string you want to write to the file. Lets see the example.


#Open the file called "jokes.txt" for writing
set out [open "jokes.txt" w]
puts $out "Computers make very fast, very accurate mistakes."

Notice that I created a variable called 'out'. That will store the ID of the opened file. Always open a file in this way - otherwise they won't be of much use. Then we use that ID to write to the file using the command 'puts'. Now the file called "jokes.txt" has one line. Next we have to close the file.

close

Syntax:
close ?channelId?

This command closes the channel. Always do this - else you will cry later. Lets move on to the ever growing example...


#Open the file called "jokes.txt" for writing
set out [open "jokes.txt" w]
puts $out "Computers make very fast, very accurate mistakes."
close $out

After we close the file, we decide that we have to put more lines in the file. So now we open the file again, this time in the append mode. The example grows even longer...


#Open the file called "jokes.txt" for writing
set out [open "jokes.txt" w]
puts $out "Computers make very fast, very accurate mistakes."
close $out
set out [open "jokes.txt" a]
puts $out "Computers are not intelligent. They only think they are."
puts $out "My software never has bugs. It just develops random features."
puts $out {All computers wait at the same speed.
Best file compression around:  "DEL *.*" = 100% compression
DEFINITION: Computer - A device designed to speed and automate errors.
DEFINITION: Upgrade - Take old bugs out, put new ones in.}
close $out

After we have done that, we need to read the jokes and put them back on the screen. So we learn a new command. Ladies and Gentlemen let me introduce you to...

gets

Syntax:
gets channelId ?varName?

gets will copy one line from the channel(or file) and put it in varName. If varName is not specified, the copied line will be the result of the function. We go back to our example and get the first line of the file. For that we open the file again, this time in read mode.


#Open the file called "jokes.txt" for writing
set out [open "jokes.txt" w]
puts $out "Computers make very fast, very accurate mistakes."
close $out
#Now append more jokes at the end of the file
set out [open "jokes.txt" a]
puts $out "Computers are not intelligent. They only think they are."
puts $out "My software never has bugs. It just develops random features."
puts $out {All computers wait at the same speed.
Best file compression around:  "DEL *.*" = 100% compression
DEFINITION: Computer - A device designed to speed and automate errors.
DEFINITION: Upgrade - Take old bugs out, put new ones in.}
close $out
#Opening file in read mode
set in [open "jokes.txt" r]
gets $in line
label .line -text "First Line : $line"
pack .line

This command can be used to read the whole file line by line. See the example below to see how. Don't worry about .txt insert end "$line\n---\n" - I will explain it later.


text .txt
set in [open "Jokes.txt" r]
while {[gets $in line] != -1} {
    #Do whatever you want with the $line variable
    .txt insert end "$line\n---\n"
}
close $in
pack .txt -expand 1 -fill both

This command is for reading the file line by line. Now we decide that we need to see the entire file. For that we need the read command. But remember that if we have read one line before, the read command will read only from the second line. For resetting the channel to the first position, we need the seek command.

seek

Syntax:
seek channelId offset ?origin?

The offset and origin arguments specify the position at which the next read or write will occur for channelId. Offset must be an integer (which may be negative) and origin must be one of the following - start, current or end.

Now we have to read the file contents. So we move on to...

read

Syntax:
read channelId ?numChars?

read will take numChars characters from the channel and return it. If numChars is not specified, the whole file is read and its content will be returned. You can read a file and then get all the lines into a list with every line as an item in the list. This can be done by...


set in [open "file.txt" r]
set contents [read $in]
close $in
set lines [split $contents "\n"]

Now every item in the list called $lines is a line of the file called "file.txt". On to the example - for the last time.


#Open the file called "jokes.txt" for writing
set out [open "jokes.txt" w]
puts $out "Computers make very fast, very accurate mistakes."
close $out
#Now append more jokes at the end of the file
set out [open "jokes.txt" a]
puts $out "Computers are not intelligent. They only think they are."
puts $out "My software never has bugs. It just develops random features."
puts $out {All computers wait at the same speed.
Best file compression around:  "DEL *.*" = 100% compression
DEFINITION: Computer - A device designed to speed and automate errors.
DEFINITION: Upgrade - Take old bugs out, put new ones in.}
close $out
#Opening file in read mode
set in [open "jokes.txt" r]
gets $in line
label .line -text "First Line : $line"
pack .line
seek $in 0 start 
set contents [read $in]
close $in
label .full -text "Full file Contents... \n$contents"
pack .full

There. That's about it with file handling. Now lets move on to juicier topics.

Previous
Procedures 
Next
TK 

Comments

Anonymous at 05 Feb, 2007 01:33
hello,
i need a information, how can we interface the scprit with the devices like routers and swiches.
if you come to know about this get ae a mail. if you have a sample scprit send to me.

Regards
narasimha
Reply to this.
Binny V A at 05 Feb, 2007 05:41
I think you can do this with sockets. Tcl supports sockets - you can get more details on this subject here...
Socket
socket - Open a TCP network connection

I have not used sockets in Tcl yet - so I don't know much about this topic.
Reply to this.
Anonymous at 05 Feb, 2007 05:54

Hi all,

How to open a socket with a server [our application] running on remote
Windows machine? I need to communicate with that server by opening a
socket. I need your help. Its very urgent.

Thanks & Regards,
Narasimha.V
Reply to this.
raghu at 12 Apr, 2007 08:05
Hi all,

How can i open a tcl file and copy a variable from that file and add to a new variable in the current file??

suppose
file "xyz.tcl" contains

set x 24


and when i open the file xyz.tcl in some file can the $x be used to update some other value??
Reply to this.
Binny V A at 12 Apr, 2007 08:52
How about reading the file and then using 'eval' function to execute the statements that you want. Or, if you want to execute the entire file, use the 'source' function. Hope this helps.
Reply to this.
Anonymous at 09 Oct, 2008 10:20
how about reading a each line(here each line is a tcl command) of file and execute in the main program. can anybody please tell me

Reply to this.
Ankur at 13 Apr, 2007 11:28
Yes , you can use that.

You need to include xyz.tcl in other file where you want to use it.
[ Syntax : source xyz.tcl]

Hope this helps.
Reply to this.
venu kosuri at 20 Aug, 2007 10:47
How to use ssh to login to a remote machine in TCL script and input commands to the remote machine
Reply to this.
Mahesh V. Shet at 11 Sep, 2007 06:01
Hi,

Its easy to open a socket in tcl using a tcl socket command. The syntax is as follows.

set sock [socket $hostname $portname ?myaddr? ?myport?]

The arguments within a question mark are optional. Now puts and gets on $sock will write to socket and read from socket.

Second point, if you want to ssh to a remote a host better option is to use Expect package of TCL. Its a tool for interactive applications.
Reply to this.
Anonymous at 17 Sep, 2007 07:24
HI,
Just want to know in TCL/TK how to get data from text window and dump in to one file.
Reply to this.
Anonymous at 30 Jan, 2008 02:47
Hi All,

I have one problem, i have tried out all the options but of useless. i want my script to ask for input and curser to stay at same line when i execute gets command. what are the way to do this?
Eg:
Enter your number : _
Reply to this.
Anonymous at 12 Feb, 2008 03:56
Just a typo, Change Jokes.txt to jokes.txt in example above

text .txt
set in [open "Jokes.txt" r]
...

Reply to this.
Anonymous at 03 Apr, 2008 08:21
Hi,

I could send data to serial port (e.g. com1).

-open com1 w+
-fconfigure {channelId} -mode 9600,n,8,1
-puts {channelId} 0123

But it is ASCII (0=x30, 1=x31, 2=x32, 3=x33).

How can I send binary data to serial port?

Thanks,
Reply to this.
Anonymous at 21 May, 2008 04:25
hi
how can i read data from a file which is continouslly getting data from another exec command...
i.e i am executing one c program which is writing some data into the file and at the same time i need the data written to file on my text area...how to do that..
Reply to this.
Anonymous at 24 May, 2008 12:10
Exec always return only the first line of output. You have to use 'open "|command" r' instead of 'exec command'. This will open an ordinary tcl channel and then you'll be able to read and write from and to the pipe (so, capturing command's stdout and writing to it's stdin).
Reply to this.
Anonymous at 27 May, 2008 02:50
My problem is how to flush the data from stdin to textarea..
Actually one f my text file is growing because of one c file open command ..
now i need to read the contents of the same file at that instant only and redirect the output to text area...i am getting line by line output on console window...but in text area once the command gets executed then only its showing the output...
can u help me in it
for example
open "|./log"
this file is giving input to abc.txt
now what i need is to get the ouptut on text area
rather than on console
i am using .textarea insert end $line
but once all the lines gets buffered and file stops to grow then only its displaying the output
help me out

Reply to this.
Anonymous at 07 Jun, 2008 12:32
Try to check the status of the file from time to time, say, every five seconds. It's pretty easy with 'after' command.
Reply to this.
Anonymous at 20 Sep, 2008 07:37
It is reaching eof file so only the read contents are displayed..
Below is my code..
I am executing ping 10.100.12.20 >>ping_log.txt
proc createLog {} {
global base
set naptime 10
set fd [open ping_log.txt r]
while {[gets $fd out] >= 0} {
$::status configure -state normal #my Scrolled text window..
$::status insert end "$out\n" #text window.
after $naptime
}
catch {close $fd}
$::status configure -state disabled
}
Reply to this.
Anonymous at 24 May, 2008 12:08
Use a binary data in TCL is so tricky...

First, you have to configure open channel to be binary (so TCL wont do any translation there):

# ...
set chan [open file.txt r]
fconfigure $chan -encoding binary
# ...

When you communicate with such channel, be aware. If you will to use internal tcl commands (string etc.), use "binary scan" after reading channel or "binary format" before writing to channel, to convert between byte-string and tcl's unicode representation.

It is wise to read the whole 'binary' documentation page and links from there.
Reply to this.
Rajat Gujral at 31 Dec, 2009 05:22
use binary
Reply to this.
Anonymous at 20 May, 2008 04:17
i have one text file i have to read that file and have to store some lines of that text file to a new text file
Reply to this.
Anonymous at 28 May, 2008 04:14
Hello all,
how do i link an executable C file with the button ????? Plz help..
thanks,
Reply to this.
kokoytams at 28 May, 2008 11:14
i tried some of the examples, some of them works but in the script reading a line from a different
file, line by line, i dont know it does not work, why?
Reply to this.
kokoytams at 28 May, 2008 11:20
ok, i see where i went wrong...
thanks
but i have another problem, how can i compare two files?
Reply to this.
Anonymous at 30 May, 2008 06:20
Hi,
How to open multiple files at the same time in tcl script ?
Reply to this.
Anonymous at 07 Jun, 2008 12:33
like this:

set f1 [open "file1.txt" "r"]
set f2 [open "file2.txt" "r"]
set f3 [open "file3.txt" "w"]

# ...
# some code, which reads files f1 and f2 and writes to f3
# ...

close $f1
close $f2
close $f3
Reply to this.
Anonymous at 10 Jun, 2008 11:36
how do we search for particular cells in a file after searching how will i be able 2 use the contents of tht particular cell.
Reply to this.
Binny V A at 13 Jun, 2008 09:22
What do you mean by cells? Are you using a plain text format file or something else?
Reply to this.
Anonymous at 16 Jun, 2008 01:40
well cells as in subfiles
Reply to this.
Anonymous at 17 Jun, 2008 12:21
Hey, i was wondering if there is a way to create a new folder that will contain a file also created by the script.
Reply to this.
Anonymous at 17 Jun, 2008 12:31
nvm, figured it out (file mkdir)
Reply to this.
Anonymous at 29 Aug, 2008 07:41
Can you read a file that has say 5 fields per line - date, acct#, phone#, code1, code2. If the record is there but code2 is not in the line can I append code2 to that line and write it back to the file?
Reply to this.
Anonymous at 17 Oct, 2008 05:04
Hi,

can u please tell me which command is used to see the history of a file and file system.

Regards,
Preethi.
Reply to this.
Michael at 05 Nov, 2008 07:26
Hi,
I am no tcl expert but hoping that there is someone out there.
How do I write a script that change content in a xml file and then save it to a new file?

I want to change <Port>80</Port ranging from 80 to 89 and creating 10 new files with this changes

thx,
Michael
Reply to this.
Anonymous at 09 Feb, 2009 03:37

In this file, I have various segments begining with *xx, wherr xx can be anything. Always * plus 2 characters. I need to start

new line when any 3 characters = *xx.

How do I accomplish that?

I do not want to re-write the file.

Input file is stored locally.
Reply to this.
Anonymous at 17 Feb, 2009 03:08
create a file that contains only net names present in a netlist

<input_file> <output_file>

where input_file : netlist file

output_file : output where net names will be stored

Reply to this.
Anonymous at 19 May, 2009 03:28
Hello.,

I have a file haveing the contents in the following format.

12 12354.21 4253.154
14 12.12 4578
2 12 45.36 etc.....

I want to do the manupulation of each colums (by adding all the contents columnwise, here 3 columns are there.)

I want to know how can i read the fine...can give me any logic for this.?
Reply to this.
Anonymous at 16 Sep, 2009 06:12
Hi,

How to insert a line in the text file (beginning, after the 4th line, etc.) in tcl? Thanks.
Reply to this.
Anonymous at 25 Sep, 2009 07:13
Hi,
Can any one tell me how to create one new file while executing the tcl file.
Reply to this.
Anonymous at 06 Oct, 2009 11:23
My problem is how to flush the data from stdin to textarea..
Reply to this.
pooja at 23 Oct, 2009 08:06
Hi All,
I have a .tcl file with some data. few data i need to write in .txt file and save it.
please help how to do this.....
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.
Subscribe to Feed