The Wayback Machine - https://web.archive.org/web/20230617093316/https://www.geeksforgeeks.org/how-to-remove-all-directories-and-files-in-golang/
Skip to content
Related Articles
Open In App

Related Articles

How to Remove All Directories and Files in Golang?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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
Similar Reads