ZetCode

Tcl files and directories

last modified November 24, 2026 Tcl 8.6

Tcl treats files through two layers. The file command works on names: it joins and splits paths, reports whether something exists, and copies, renames or deletes it. The open command returns a channel, and the ordinary input and output commands gets, puts and read work on that channel. Both layers are portable, so the same script runs on Linux, macOS and Windows.

This article works in a small project directory. It contains a configuration file, a log file, a notes file, a data directory with a report and a logs directory with one nested archive. The outputs below were captured in that directory, and the later sections create and change files as they go.

Path handling with file join and friends

Hard coded slashes break on Windows, so build paths with file join. It inserts the platform separator and removes duplicate separators. The reverse operation is file split, and the remaining subcommands take a path apart without touching the disk.

paths.tcl
set path [file join /srv shop conf app.ini]

puts "joined:    $path"
puts "tail:      [file tail $path]"
puts "dirname:   [file dirname $path]"
puts "extension: [file extension $path]"
puts "rootname:  [file rootname $path]"
puts "pathtype:  [file pathtype $path]"
puts "separator: [file separator]"

set parts [file split $path]
puts "split:     $parts"
puts "rejoined:  [file join {*}$parts]"

puts "relative:  [file dirname report.txt]"

file tail returns the last component, file dirname returns everything before it, and file extension includes the dot. file rootname removes the extension. The split result starts with the root separator, and file join {*}$parts expands the list back into separate arguments. For a bare file name, the dirname is the current directory, printed as a single dot. The Tcl file command page documents the remaining path subcommands.

$ tclsh paths.tcl
joined:    /srv/shop/conf/app.ini
tail:      app.ini
dirname:   /srv/shop/conf
extension: .ini
rootname:  /srv/shop/conf/app
pathtype:  absolute
separator: /
split:     / srv shop conf app.ini
rejoined:  /srv/shop/conf/app.ini
relative:  .

exists, isfile, isdirectory, size and stat

Before opening a file, check whether it is there and what it is. file exists, file isfile and file isdirectory answer the common questions, and file size returns the length in bytes. All of them return 0 or 1 instead of raising an error for a missing name.

stat.tcl
set path data/report.txt

puts "exists:      [file exists $path]"
puts "isfile:      [file isfile $path]"
puts "isdirectory: [file isdirectory $path]"
puts "size:        [file size $path]"
puts "readable:    [file readable $path]"
puts "writable:    [file writable $path]"

puts "missing:     [file exists data/missing.txt]"
puts "missing dir: [file isdirectory data/missing.txt]"

file stat $path info
puts "stat keys:   [lsort [array names info]]"
puts "stat type:   $info(type)"
puts "stat size:   $info(size)"
puts "stat mode:   [format %o $info(mode)]"

The report exists, is a regular file and has 46 bytes. Asking about a missing name simply returns 0; it is not an error. In Tcl 8.6 file stat takes a variable name and fills an array with the fields shown in the array names line. The mode includes the file type bits, so 100664 means a regular file with read and write permission for the owner and group and read permission for others; the permission bits depend on the umask used when the file was created. The Tcl glob command page covers finding names that match a pattern.

$ tclsh stat.tcl
exists:      1
isfile:      1
isdirectory: 0
size:        46
readable:    1
writable:    1
missing:     0
missing dir: 0
stat keys:   atime blksize blocks ctime dev gid ino mode mtime nlink size type uid
stat type:   file
stat size:   46
stat mode:   100664

Finding files with glob

glob expands shell style patterns: * matches any sequence of characters, ? matches one character, and [abc] matches a set. The command does not recurse by itself, so a nested search adds another path component. Without -nocomplain, a pattern that matches nothing raises an error.

find_files.tcl
puts "conf files: [glob *.conf]"
puts "text files: [glob *.txt]"
puts "data:       [glob data/*]"
puts "logs:       [glob logs/*.log]"
puts "nested:     [glob logs/*/*.log]"
puts "regular:    [glob -type f *.conf *.log *.txt]"
puts "sorted:     [lsort [glob -type f -nocomplain data/* logs/*]]"
puts "no match:   [glob -nocomplain *.ini]"

The patterns are matched against the current directory, and the results keep the relative prefix. -type f keeps only regular files, which is why the logs/old directory does not appear in the sorted list. An unmatched pattern with -nocomplain returns an empty list, so the last line prints nothing after the colon. Sorting is a separate step because glob does not guarantee an order.

$ tclsh find_files.tcl
conf files: app.conf
text files: notes.txt
data:       data/report.txt
logs:       logs/app.log
nested:     logs/old/app-2026-11-23.log
regular:    app.conf app.log notes.txt
sorted:     data/report.txt logs/app.log
no match:   

Opening files and modes

open name ?access? ?permissions? returns a channel. The access mode decides what the channel can do: r reads an existing file, w creates or truncates it, and a appends to it. The plus forms r+, w+ and a+ allow both reading and writing. Always close the channel; closing flushes buffered output.

modes.tcl
set path data/report.txt

set fh [open $path w]
puts $fh "quarterly report"
puts $fh "region: Europe"
close $fh

set fh [open $path a]
puts $fh "status: draft"
close $fh

set fh [open $path r]
set content [read $fh]
close $fh

puts "--- $path ---"
puts -nonewline $content
puts "characters: [string length $content]"

The w mode starts an empty file; the two puts lines write two lines because puts adds a newline by default. The a mode adds the third line without truncating the file. Reading then returns the complete text, and puts -nonewline prints it without adding another newline. The final count includes the three newline characters, which is why it is 46 and not 43. The Tcl open command page lists encoding and translation options for text and binary data.

$ tclsh modes.tcl
--- data/report.txt ---
quarterly report
region: Europe
status: draft
characters: 46

Reading and writing with gets, puts and read

A channel can be read line by line with gets or in one piece with read. gets channel lineVar stores one line without its newline and returns the number of characters read, or -1 at end of file. That return value is what a while loop tests; the line itself may be empty.

lines.tcl
set path app.log

set fh [open $path r]
set count 0
while {[gets $fh line] >= 0} {
    incr count
    puts "$count: $line"
}
close $fh
puts "lines: $count"

set fh [open $path r]
set first [gets $fh]
set rest [read $fh]
puts "first:   $first"
puts "rest:    [string length $rest] characters"
puts "at eof:  [eof $fh]"
puts "gets:    [gets $fh line]"
close $fh

The loop prints each line with a number and counts three lines. The second channel reads the first line separately and then the remainder with read, which returns everything from the current position to the end. After that read the channel is at end of file, eof returns 1, and a further gets returns -1. Opening the file twice avoids seeking back to the start for the second pass.

$ tclsh lines.tcl
1: 2026-11-24 09:00:01 INFO service started
2: 2026-11-24 09:00:05 WARNING memory low
3: 2026-11-24 09:01:12 ERROR disk full
lines: 3
first:   2026-11-24 09:00:01 INFO service started
rest:    75 characters
at eof:  1
gets:    -1

seek and tell

A channel keeps a current position measured in bytes. tell reports it and seek changes it. The offset is relative to the start, the current position or the end of the file, selected by the third argument start, current or end; the default is start.

random_access.tcl
set path data/report.txt
set fh [open $path r]

puts "start:            [tell $fh]"
gets $fh
puts "after first line: [tell $fh]"

seek $fh 0
puts "after seek 0:     [tell $fh]"
puts "first word:       '[read $fh 9]'"
puts "now at:           [tell $fh]"

seek $fh -7 end
puts "tail:             '[string trim [read $fh]]'"
close $fh

The first line is 16 characters plus a newline, so the position is 17 after gets. Seeking to 0 rewinds, and reading nine characters returns quarterly. The negative offset with end moves seven bytes back from the end, landing on the final word of the file. Byte positions and character positions are the same for ASCII text but differ for multi-byte encodings.

$ tclsh random_access.tcl
start:            0
after first line: 17
after seek 0:     0
first word:       'quarterly'
now at:           9
tail:             'draft'

Temporary files

A temporary file needs a unique name, and guessing one with clock seconds invites collisions. The file tempfile subcommand creates the file safely, returns an open channel and stores the name in a variable. The caller is responsible for closing and deleting it.

tmpfile.tcl
set fh [file tempfile path]
puts $fh "temporary data"
close $fh

puts "exists:  [file exists $path]"
puts "size:    [file size $path]"
puts "folder:  [file dirname $path]"

set fh [open $path r]
set content [read $fh]
close $fh
puts "content: [string trim $content]"

file delete $path
puts "after delete: [file exists $path]"

The channel arrives already open for writing, so the script writes, closes and reopens it for reading. The name is unpredictable but lives in the system temporary directory, which the script reports without hard coding a path. The content is trimmed because the newline added by puts would otherwise show up before the closing quote. Deleting the file at the end keeps repeated runs from filling the directory.

$ tclsh tmpfile.tcl
exists:  1
size:    15
folder:  /tmp
content: temporary data
after delete: 0

Copying, renaming and deleting

The file command also changes the filesystem. file copy and file rename take a source and a destination, and file delete removes names. Without -force these operations refuse to overwrite an existing destination or delete a file they cannot write, and they raise an error instead.

manage.tcl
file copy -force app.conf data/app.conf.bak
puts "copied:       [file exists data/app.conf.bak]"

file rename -force data/app.conf.bak data/app.conf.old
puts "renamed:      [file exists data/app.conf.old]"
puts "old name:     [file exists data/app.conf.bak]"

file delete data/app.conf.old
puts "deleted:      [file exists data/app.conf.old]"

puts "app.conf size: [file size app.conf] bytes"

The copy leaves app.conf in place. The rename then gives the copy a new name, so data/app.conf.bak no longer exists, and the delete removes the renamed file. The final size check confirms that app.conf itself was never touched. Passing several names to file delete removes them all; adding -force also removes a non-empty directory together with its contents.

$ tclsh manage.tcl
copied:       1
renamed:      1
old name:     0
deleted:      0
app.conf size: 29 bytes

Creating and walking directories

file mkdir creates a directory and any missing parents. To list a tree, a procedure can call glob -directory for one level, print each name, and recurse into the entries that are directories. Sorting each level keeps the output stable.

walk.tcl
proc walk {dir depth} {
    foreach entry [lsort [glob -nocomplain -directory $dir *]] {
        puts "[string repeat {  } $depth][file tail $entry]"
        if {[file isdirectory $entry]} {
            walk $entry [expr {$depth + 1}]
        }
    }
}

file mkdir build/parts
file mkdir build/parts/left
file mkdir build/output

set fh [open build/parts/left/panel.txt w]
puts $fh "panel description"
close $fh

walk build 0
puts "directories: [llength [glob -type d -nocomplain build/*]]"
file delete -force build
puts "build removed: [file exists build]"

The procedure prints a name, then descends when the entry is a directory. The indent is two spaces per level, produced with string repeat. The last lines count the immediate subdirectories and remove the whole tree with file delete -force, which is the recursive form. Keeping the recursion in a procedure rather than inline makes it easy to add a filter, a counter or an action for each file. The Tcl gets command and Tcl read command pages cover the channel commands used earlier.

$ tclsh walk.tcl
output
parts
  left
    panel.txt
directories: 2
build removed: 0

Source

The Tcl 8.6 manual documents the file subcommands and the channel commands separately. The file page is the reference for the path, stat, copy and delete operations, while open and the input and output commands cover channels.

This article built and inspected paths, checked names with file exists and file stat, found files with glob, opened channels in several modes and read them line by line or at random positions. It finished with temporary files, copy and delete operations, and a recursive directory walk. The Tcl command-line arguments article shows how to pass file names into such a script, and Tcl regular expressions shows how to parse the lines it reads.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Tcl Tutorials.