How to Remove All Directories and Files in Golang?

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    }
}

chevron_right


Output:

Before:



before removing all files and directories in golang

After:

after removing all files and directories in golang

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    }
}

chevron_right


Output:

Before:

before removing all files and directories in golang

After:

after removing all files and directories in golang




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.