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 (
	"io"
	"log"
	"os"
) 

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

Path operations

Basepath

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)