Golang File Paths | Portable Path Operations
Tags: go, coding, programming, tutorial
Published: 2024-07-14 03:25:48


## Introduction

![MindMap](https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/authcode/?code=OTdlZTljMjNjMDZkNWY1YWFmM2JhZDE4OTZkMWMwNjlfZjQ0ODU4ZGEwYjJmMjAzMDQxZWJiY2UzZGE5YzhiZTlfSUQ6NzM5MTMyNzQ1MzIwMzk1NTcxNV8xNzIwOTI3NTQ2OjE3MjEwMTM5NDZfVjM)

The `filepath` package in Golang provides functions to parse and construct file paths in a way that is portable between operating systems.


## File Paths

In [this lab](https://labex.io/tutorials/file-paths-15475), you need to use the `filepath` package to perform various operations on file paths, such as constructing paths in a portable way, splitting a path into directory and file components, checking whether a path is absolute, finding the extension of a file, and finding a relative path between two paths.

- Use `Join` to construct paths in a portable way.
- Use `Dir` and `Base` to split a path into directory and file components.
- Use `IsAbs` to check whether a path is absolute.
- Use `Ext` to find the extension of a file.
- Use `TrimSuffix` to remove the extension from a file name.
- Use `Rel` to find a relative path between two paths.

```sh
$ go run file-paths.go
p: dir1/dir2/filename
dir1/filename
dir1/filename
Dir(p): dir1/dir2
Base(p): filename
false
true
.json
config
t/file
../c/t/file

```

There is the full code below:

```go
// The `filepath` package provides functions to parse
// and construct *file paths* in a way that is portable
// between operating systems; `dir/file` on Linux vs.
// `dir\file` on Windows, for example.
package main

import (
	"fmt"
	"path/filepath"
	"strings"
)

func main() {

	// `Join` should be used to construct paths in a
	// portable way. It takes any number of arguments
	// and constructs a hierarchical path from them.
	p := filepath.Join("dir1", "dir2", "filename")
	fmt.Println("p:", p)

	// You should always use `Join` instead of
	// concatenating `/`s or `\`s manually. In addition
	// to providing portability, `Join` will also
	// normalize paths by removing superfluous separators
	// and directory changes.
	fmt.Println(filepath.Join("dir1//", "filename"))
	fmt.Println(filepath.Join("dir1/../dir1", "filename"))

	// `Dir` and `Base` can be used to split a path to the
	// directory and the file. Alternatively, `Split` will
	// return both in the same call.
	fmt.Println("Dir(p):", filepath.Dir(p))
	fmt.Println("Base(p):", filepath.Base(p))

	// We can check whether a path is absolute.
	fmt.Println(filepath.IsAbs("dir/file"))
	fmt.Println(filepath.IsAbs("/dir/file"))

	filename := "config.json"

	// Some file names have extensions following a dot. We
	// can split the extension out of such names with `Ext`.
	ext := filepath.Ext(filename)
	fmt.Println(ext)

	// To find the file's name with the extension removed,
	// use `strings.TrimSuffix`.
	fmt.Println(strings.TrimSuffix(filename, ext))

	// `Rel` finds a relative path between a *base* and a
	// *target*. It returns an error if the target cannot
	// be made relative to base.
	rel, err := filepath.Rel("a/b", "a/b/t/file")
	if err != nil {
		panic(err)
	}
	fmt.Println(rel)

	rel, err = filepath.Rel("a/b", "a/c/t/file")
	if err != nil {
		panic(err)
	}
	fmt.Println(rel)
}

```


## Summary

The `filepath` package in Golang provides functions to work with file paths in a portable way. By using these functions, you can construct paths, split them into directory and file components, check whether they are absolute, find the extension of a file, and find a relative path between two paths.

---

> 🚀 Practice Now: [File Path Handling in Golang](https://labex.io/tutorials/file-paths-15475)

---

## Want to Learn More?

- 🌳 Learn the latest [Go Skill Trees](https://labex.io/skilltrees/go)
- 📖 Read More [Go Tutorials](https://labex.io/tutorials/category/go)
- 💬 Join our [Discord](https://discord.gg/J6k3u69nU6) or tweet us [@WeAreLabEx](https://twitter.com/WeAreLabEx)