How to Delete or Remove a File in Golang?

In the Go language, you are allowed to remove the existing file with the help of the Remove() method. This method removes the specified file from the director or it also removes empty directories. If the given path is incorrect, then it will throw an error of type *PathError. It is defined under the os package so, you have to import os package in your program for accessing Remove() function.

Syntax:

func Remove(file_name string) error

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate how to 
// remove files from the default directory
package main
   
import (
    "log"
    "os"
)
   
func main() {
  
    // Removing file from the directory
    // Using Remove() function
     e := os.Remove("GeeksforGeeks.txt")
    if e != nil {
        log.Fatal(e)
    }
}

chevron_right


Output:

Before:



Before Deleting a File in Golang

After:

After Deleting a File in Golang

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate how to remove
// files from the specified directory
package main
    
import (
    "log"
    "os"
)
    
func main() {
   
    // Removing file
    // Using Remove() function
    e := os.Remove("/Users/anki/Documents/new_folder/GeeksforGeeks.txt")
    if e != nil {
        log.Fatal(e)
  
   
}

chevron_right


Output:

Before:

Before Deleting a File in Golang

After:

After Deleting a File 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.