filepath package provides functions to parse and construct file paths in a way that is portable across operating systems. It handles differences like dir/file on Linux vs. dir\file on Windows automatically.
Why Use filepath?
The
filepath package ensures your code works correctly across different operating systems by handling platform-specific path separators and conventions.Joining Paths
Usefilepath.Join to construct paths portably:
Path Normalization
filepath.Join also normalizes paths by removing superfluous separators and directory changes:
Splitting Paths
Directory and Base
Split in One Call
filepath.Dir
Returns the directory portion of a path
filepath.Base
Returns the last element of a path (filename)
Checking Path Types
Absolute vs Relative
What constitutes an absolute path varies by operating system.
filepath.IsAbs handles these differences automatically.Working with Extensions
Extracting Extensions
Removing Extensions
filepath.Ext returns the extension including the dot (.json), or an empty string if there is no extension.Relative Paths
Find a relative path between a base and target:Complete Example
Common Operations
- Join Paths
- Get Directory
- Get Filename
- Get Extension
- Check Absolute
- Make Relative
Best Practices
Always use filepath.Join
Always use filepath.Join
Never manually concatenate path components with
/ or \. Use filepath.Join to ensure cross-platform compatibility.Use filepath, not path
Use filepath, not path
The
path package is for URL paths. For filesystem paths, always use path/filepath.Handle errors from Rel
Handle errors from Rel
filepath.Rel can return errors when paths are on different volumes or drives. Always check the error return value.Clean user input
Clean user input
Use
filepath.Clean to normalize user-provided paths before processing:Avoid assumptions about separators
Avoid assumptions about separators
Don’t assume
/ or \ as separators. Use filepath.Separator or os.PathSeparator if needed.Convert to absolute paths
Convert to absolute paths
When needed, convert relative paths to absolute using
filepath.Abs:Additional Functions
filepath.Clean
Returns the shortest path equivalent to path by removing
. and .. elementsfilepath.Abs
Returns an absolute representation of path
filepath.Match
Reports whether name matches the shell pattern
filepath.Glob
Returns names of all files matching pattern
Related Topics
Directories
Learn how to work with directories
Reading Files
Learn how to read files in Go