How to Delete or Remove File and Directory in Go

To delete a file in Golang, you can “use the os.Remove() function.” If there is an error, that will be of type *PathError.

PathError means the program could not find the provided file in a particular path, throwing an error.

Syntax

func Remove(name string) error

Parameters

name: It accepts the filename(filepath).

Example 1: Removing a file

Before removing an app.txt file from the current directory, it looks like this:

Before removing a file

Write the deletion code in app.go file.

package main

import (
  "fmt"
  "log"
  "os"
)

func main() {
  // Define the file path
  filePath := "my_text_file.txt"

  // Remove the file
  err := os.Remove(filePath)
  if err != nil {
    log.Fatalf("Error removing file: %v", err)
  }

  fmt.Printf("File %s removed successfully\n", filePath)
}

Output

File my_text_file.txt removed successfully

After deleting a file, the current working directory looks like this:

Screenshot of removed file from current working directory

Example 2: Delete an entire directory

Go os.RemoveAll() function is “used to delete the complete path.” That means it will delete the entire directory, subdirectories, and files.

Let’s say in our current directory, we have a new directory called newDir. The directory is empty and we will remove that directory.

Before removing, our current working directory looks like this:

Screenshot of before removing a directory

package main

import (
  "fmt"
  "log"
  "os"
)

func main() {
  // Define the directory path
  dirPath := "newDir"

  // Remove the directory
  err := os.RemoveAll(dirPath)
  if err != nil {
    log.Fatalf("Error removing directory: %v", err)
  }

  fmt.Printf("Directory %s removed successfully\n", dirPath)
}

Output

Directory newDir removed successfully

After removing a directory:

Screenshot of after removed directory of current working directory

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.