Open In App

How to Remove All Directories and Files in Golang?

Improve
Improve
Like Article
Like
Save
Share
Report

In Go language, you are allowed to remove all the directories and files from a directory or folder with the help of RemoveAll() function. This function removes all the directories and files from the path you will pass to this function. It will remove everything from the specified path, but returns the first error it encounters. If the specified path does not exist, then this method returns nil. If this method throws an error, then it will be of type *PathError. It is defined under the os package so, you have to import os package in your program for accessing RemoveAll() function.

Syntax:

func RemoveAll(path string) error

Example 1:




// Golang program to illustrate how to 
// remove all the files and directories
// from the default directory
package main
  
import (
    "log"
    "os"
)
  
func main() {
  
    // Remove all the directories and files
    // Using RemoveAll() function
    err := os.RemoveAll("/Users/anki/Documents/go")
    if err != nil {
        log.Fatal(err)
    }
}


Output:

Before:

before removing all files and directories in golang

After:

after removing all files and directories in golang

Example 2:




// Golang program to illustrate how to remove
// all the files and directories from the
// new directory
package main
  
import (
    "log"
    "os"
)
  
func main() {
  
    // Remove all the directories and files
    // Using RemoveAll() function
    err := os.RemoveAll("/Users/anki/Documents/new_folder/files")
    if err != nil {
        log.Fatal(err)
    }
}


Output:

Before:

before removing all files and directories in golang

After:

after removing all files and directories in golang



Last Updated : 23 Mar, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads