Delete files in Golang

Deleting files is important when we want to do routine work with files. E.g. we save some log data and then after some time we may want to remove it automatically. This file deletion can be easily done in Go. In this post, we are going to discuss how to delete files in Go.

Remove files using os package

In order to remove a single file, we need to import the os package. It contains the Remove() and RemoveAll functions.

1. Delete a single file

The Remove function from the os package takes the file path as a parameter and deletes the file. It only deletes a single file.

os.Remove("path/to/file")

Below is an example of using the remove function.

package main

import (
    "fmt"
    "os"
)

func main() {
  err := os.Remove("test.txt")  // remove a single file
  if err != nil {
    fmt.Println(err)
  }
}

Recommended: Download Files in Golang.

2. Delete an entire directory

The RemoveAll() function completely deletes the path. That means it will delete the entire directory and all the subdirectories and files inside it. Here is an example of how to delete a directory in Golang.

package main

import (
    "fmt"
    "os"
)

func main() {
  err := os.RemoveAll("directoryname")  // delete an entire directory
  if err != nil {
    fmt.Println(err)
  }
}

This function deletes the entire directory.

In case of confusion, for deleting a single file use the Remove() function and if you want to delete the entire directory use the RemoveAll() function.