1. A path is not just a string
When you start working with files, the first thought is usually: “Well, a path is a string... I’ll just concatenate "data/" + name + ".txt" — and done”. This is the moment when the developer in the next room starts quietly crying on Windows, and your future code looks at you with the expression “we’ll meet again”. In Go, a path is indeed represented as a string, but it is a string with strict rules that depend on the operating system and the runtime context.
The most important idea of today’s lecture is: it is better to treat a path as a value that you build and normalize with special functions, rather than as a piece of text that you “roughly correctly” glued together with concatenation.
Imagine the address on an envelope. Formally, it is just text, but if you mix up the ZIP code or the street, the letter will not arrive. Paths are similar: you can write something that looks like a path, but the OS may interpret it differently than you expected.
2. Two worlds of paths: path and path/filepath
It is very easy to get confused by the names: “path” and “filepath” — both are about paths, right? Yes... but with an important difference. In Go there are two “worlds” of paths. One world is filesystem paths on your OS, the other world is universal paths with /, which often appear in URLs, inside virtual file systems, in embed resources, and similar things.
For this lecture, let’s fix a simple rule that in practice saves time and nerves: if the path refers to a file/directory on disk — use path/filepath. If you are working with “logical paths” with slashes / that do not depend on the OS, then path is the right choice.
Let’s compare them in a table (it is really useful to reread until it sinks in):
| What you are building | Example | Which package to use | Why |
|---|---|---|---|
| Path to a file on disk | |
|
Respects OS rules (separators, absolute path specifics) |
| URL / path inside a resource | |
|
That is almost always a “slash world” that does not depend on the OS |
Mini example: filepath.Join builds a path according to OS rules
Instead of manually concatenating strings, we build the path from parts:
package main
import (
"fmt"
"path/filepath"
)
func main() {
p := filepath.Join("data", "todo", "items.txt")
fmt.Println(p) // on Windows it will use '\', on Linux/macOS '/'
}
The important effect here is not just “beauty”. You stop guessing which separator is needed, and you stop making mistakes like "data//todo///items.txt".
3. Separators and portability
When your code runs only on your machine, almost everything works “for now”. But as soon as a project starts living in different environments (IDE, CI, another OS, Docker, server), it turns out that “for now” is not a strategy, but a spell.
On Windows, the traditional separator is the backslash \. On Linux/macOS, it is the forward slash /. Go can deal with this, but only if you do not start forcibly “educating” paths by hand.
There is a small but telling detail: in path/filepath there is filepath.Separator. This is literally the byte separator for the current OS. Usually you do not need to use it directly (because there is Join), but it is useful to know that the separator is not a constant "/".
Mini example: find the current OS separator
package main
import (
"fmt"
"path/filepath"
)
func main() {
fmt.Printf("separator: %q\n", filepath.Separator) // for example: '/' or '\\'
}
4. Relative and absolute paths
Relative path: “relative to what?”
A relative path is a path that does not start “from the root”. It always has a hidden question: relative to what is it being resolved? The answer: relative to the process working directory (current working directory, CWD). And that is where the magic begins (sometimes dark magic).
For example, you write data/todo/items.txt. If the program is launched from the project root, that will be one file. If you start the binary from another folder, that is a different path, and the file “suddenly disappeared”. The user swears the file exists, and the program honestly replies: “I do not know such a file”.
To avoid this being abstract, it is useful to explicitly print the current working directory from time to time.
Mini example: find the working directory
package main
import (
"fmt"
"os"
)
func main() {
wd, err := os.Getwd()
if err != nil {
fmt.Println("getwd:", err)
return
}
fmt.Println("working dir:", wd)
}
If after that you also print a relative path, it becomes obvious: a relative path is a “tail” attached to the working directory.
Absolute path: make the address explicit
An absolute path is a path that does not depend on where you launched the program from (at least in theory). It “starts from the root” of the filesystem. On Unix-like systems, that is usually a path like /home/user/project/..., on Windows — something like C:\Users\....
Absolute paths are useful in two situations.
The first is diagnostics. When something is not found, you want to see “which exact file did you try to reach”. That speeds up debugging a lot: you stop arguing with the computer in the style of “but it is definitely here”, and move to the level of “ah, you are looking in a different folder”.
The second is when you deliberately want to work only with “explicit” paths so that launching from different places does not change behavior.
Mini example: filepath.Abs
package main
import (
"fmt"
"path/filepath"
)
func main() {
abs, err := filepath.Abs(filepath.Join("data", "todo", "items.txt"))
if err != nil {
fmt.Println("abs:", err)
return
}
fmt.Println(abs)
}
Pay attention to an important psychological point: Abs returns (string, error). That already hints that “paths are not always trivial” and Go suggests treating them carefully.
Diagram: how a relative path becomes an absolute one
To reinforce the model in your head, it helps to see it once as a diagram. The idea is simple: a relative path is not a full address, it is an address missing the “city”. The city is CWD.
flowchart TD
A["Working directory (CWD) for example: /home/alex/project"] --> C["Joining according to OS rules (CWD + relative path)"]
B["Relative path for example: data/todo/items.txt"] --> C
C --> D["Absolute path for example: /home/alex/project/data/todo/items.txt"]
If you keep this diagram in mind, 80% of the weirdness around “the path looks correct, but does not work” stops being mysterious.
5. Building and normalizing paths
filepath.Join: building without manual concatenation
Building paths with + is like repairing a spaceship with duct tape: sometimes it even flies, but it should not become a habit.
filepath.Join does two things that are especially important for beginners.
- First, it inserts the correct separators between parts (and does not insert extra ones).
- Second, it correctly handles situations where the parts already contain separators. For example, if someone passed "data/" instead of "data", Join will still produce a sensible path, and you will not get "data//todo".
Mini example: path to the data of a tutorial app
Imagine we have a simple console to-do app, and we decided to store data in data/todo/items.txt. We will start with a small function that builds the path.
package main
import (
"fmt"
"path/filepath"
)
func todoItemsPath() string {
return filepath.Join("data", "todo", "items.txt")
}
func main() {
fmt.Println(todoItemsPath()) // for example: data/todo/items.txt
}
So far this looks boring. But that boredom is good: it means the path is built the same way every time and predictably, and that means fewer surprises.
filepath.Clean: normalizing “dirty” input
Sooner or later, a path will reach you not from your constant in code, but from the outside: a command-line argument, a config, an environment variable, user input. And that path may be “dirty”: with . (current directory), with .. (up one level), with double slashes, with extra elements.
filepath.Clean(p) converts a path to a normalized form. It does not “check whether a file exists”, does not “fix” permissions, and does not “make a path safe” in every sense. It simply makes the string representation of the path more tidy and predictable.
Mini example: cleaning a path
package main
import (
"fmt"
"path/filepath"
)
func main() {
raw := "data//todo/../tmp/./file.txt"
fmt.Println("raw: ", raw)
fmt.Println("clean:", filepath.Clean(raw))
}
In the end, Clean will remove . and collapse .. where possible, and also bring repeated separators into normal form.
Here it is useful to remember a practical code-reading rule: first you build and clean the path as a value, and only then use it in file operations. This makes the code simpler: “the path is malformed” errors and “the file could not be opened” errors do not get mixed into one mess.
path.Clean and filepath.Clean: do not mix up the worlds
From the naming perspective, the functions look the same — Clean. But the world’s meaning is different.
path.Clean works in the world of “always /”. filepath.Clean works in the world of “as on the current OS”. If you accidentally apply path.Clean to disk paths, on some platforms it may look “sort of fine”, but overall that is a bad bet for the future.
So the rule remains rock solid: disk — filepath, not disk — path.
Paths in an application: functions instead of “magic strings”
When a project grows, magic strings with paths start multiplying like rabbits (and complicate life about as much). At some point you will find three different places where "data/todo/items.txt" is written, and two more places where someone decided that "./data/todo/items.txt" is better.
A simple technique helps you keep control: make functions that build paths centrally. This is not “architecture for the ages”, just basic hygiene.
Mini example: base data directory + file inside it
package main
import (
"path/filepath"
)
func dataDir() string {
return filepath.Join("data", "todo")
}
func itemsFilePath() string {
return filepath.Join(dataDir(), "items.txt")
}
Right now these functions do not validate anything and do not create anything — and that is normal. We are solving the task of this step: not storing a path as a random piece of text.
6. Diagnosing paths and errors
%q and invisible characters
Debugging paths often turns into theater of the absurd because of invisible characters. A trailing space, a tab, a newline, a non-printable character — and you see a “seemingly normal” path that is actually not normal.
That is why, for diagnostics, it is better to print paths as string literals — with quotes and escaping. That is what %q does.
Mini example: printing a path “as is” and “in quotes”
package main
import (
"fmt"
)
func main() {
p := "data/todo/items.txt \n"
fmt.Println(p) // looks suspiciously “normal”
fmt.Printf("%q\n", p) // you can see the space and \n
}
Errors: add context to the operation and the path
Even though we are not opening files yet today, it is worth fixing the mindset in advance: in file operations, an error is not an exception, but a normal result. So when you get an error from functions like Abs or later from os.Open, you will almost always need to add context: “which exact path”, “which operation”.
And here the familiar wrapping idea comes up: we wrap the error while preserving the cause so it can be recognized at a higher level (via errors.Is/errors.As). In Go, %w in fmt.Errorf is used for this, and that is an important difference from “just print the error as text”.
This note may seem premature, but in practice it saves hours: you start writing error messages so that in a week you will say “thank you” to yourself, rather than “who wrote this and why does this person hate me”.
7. Typical mistakes when working with paths
Mistake #1: building a path by string concatenation.
It usually starts with an innocent "data/" + name, and ends with a quest of “why can’t CI find the file”. filepath.Join solves most of these problems right away, because it knows how to insert separators correctly and not create extra ones.
Mistake #2: using path.Join for a file path on disk.
path lives in the world of /, while your OS filesystem may live by other rules. For files on disk, use path/filepath, even if “it already works on macOS for me”.
Mistake #3: treating a relative path as an “absolute truth”.
A relative path always depends on the process working directory. If the launch changes (IDE, terminal, service), the meaning of the path changes too. When behavior must be stable, it is useful to diagnose os.Getwd() and, if needed, convert the path to an absolute one with filepath.Abs.
Mistake #4: not normalizing a “dirty” path.
If a path comes from outside and contains . and .., it is better to bring it to a predictable form with filepath.Clean. This will not make the path “safe in every sense”, but it greatly reduces the number of accidental mismatches and strange string comparisons.
Mistake #5: debugging a path with fmt.Println, and then being surprised.
If a path contains spaces or non-printable characters, Println can mislead you: you may not visually notice the problem. For diagnostics, use fmt.Printf("%q\n", p), so you can see the string “honestly”, with all escaping.
GO TO FULL VERSION