File Path Handling in Golang | Challenge

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/FileOperationsGroup(["`File Operations`"]) go/FileOperationsGroup -.-> go/file_paths("`File Paths`") subgraph Lab Skills go/file_paths -.-> lab-15395{{"`File Path Handling in Golang | Challenge`"}} end

File Paths

In this challenge, 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.

Requirements

  • 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.

Example

$ 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

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.

Other Go Tutorials you may like