Working with the filesystem
There are many aspects of filesystems that are platform-specific. This section talks about portable ways of working with filesystems.
Working with filenames
Use path/filepath
package to work with filenames in a portable way.
How do to it...
- To build a path from several path segments, use
filepath.Join
:fmt.Println(filepath.Join("/a/b/","/c/d") // Prints /a/b/c fmt.Println(filepath.Join("/a/b/c/d/","../../x") // Prints a/b/x
Note that
filepath.Join
does not allow consecutive separators, and interprets".."
correctly. - To split a path to its directory and filename parts, use
filepath.Split
:fmt.Println(filepath.Split("/home/bserdar/work.txt")) // dir: "/home/bserdar" file: "work.txt" fmt.Println(filepath.Split("/home/bserdar/projects/")) // dir: "/home/bserdar/projects/" file: ""
- Avoid using path separators (
/
and\
) in your code...