Go filesystem operations

Notes on Go filesystem operations.

Copying files

Go does not have an utility method to copy files. We have to rely on writing our own implementation using the reading and writing functionality in other packages. As an example:

package main 

import (

func main() { 
	from, err := os.Open("./foo.txt")
	if err != nil { 
	defer from.Close() 
	to, err := os.OpenFile("./bar.txt", os.O_RDWR|os.O_CREATE, 0666) 
	if err != nil { 
	defer to.Close() 
	_, err = io.Copy(to, from) 
	if err != nil { 

Path operations


To get the basepath of a path string we use the Dir method:

filepath.Dir("/etc/foo/file.txt") // "/etc/foo"

Check if directory exists

if _, err := os.Stat("/etc/foo/"); os.IsNotExist(err) {
	// do something because it does not exist

Create nested directories

Use MkdirAll:

os.MkdirAll("/etc/long/nested/path/to/create", os.ModePerm)