File Organizer
Start with File Organizer
Learn file organizer through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of file organizer.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A file organizer inspects file types and moves items into destination directories. Operate only within a user-selected root, validate paths, handle filename conflicts and report failures.
The example creates its own temporary workspace so it cannot reorganize the reader’s actual files.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Production checklist: use filepath.Rel or another robust containment check, consider symlinks, handle duplicate filenames, record moves, add dry-run/undo behavior, and test permission errors.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
)
func main() {
root, err := os.MkdirTemp("", "go-organizer-")
if err != nil {
panic(err)
}
defer os.RemoveAll(root)
for _, name := range []string{"report.txt", "data.csv"} {
if err := os.WriteFile(filepath.Join(root, name), []byte("demo"), 0600); err != nil {
panic(err)
}
}
for _, name := range []string{"report.txt", "data.csv"} {
extension := strings.TrimPrefix(filepath.Ext(name), ".")
folder := filepath.Join(root, extension)
if err := os.MkdirAll(folder, 0700); err != nil {
panic(err)
}
if err := os.Rename(filepath.Join(root, name), filepath.Join(folder, name)); err != nil {
panic(err)
}
fmt.Println(name, "->", extension+"/")
}
}
Output
report.txt -> txt/
data.csv -> csv/Trace what the program does
Two temporary files are created. Each extension becomes a subfolder name, and os.Rename moves the file into that folder. The program prints only relative names, not random temporary paths.
Avoid common mistakes
- os.Rename may fail across filesystems; a real organizer may need a verified copy-and-remove fallback.
- Avoid overwriting existing destinations; choose an explicit conflict policy.
Try it yourself
Organize three file extensions, add a dry-run mode, and reject files outside an authorized root.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced File Organizer in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.