Skip to main content

How to Delete Files in Golang

In our previous tutorial, we have explained how to Read File Line by Line in Golang. In this tutorial, we will explain how to Delete Files in Golang.

While working with files and directories, sometimes we need to delete specific file or all files from a directory. It’s very easy in Golang to delete a file. There are a Remove() and RemoveAll() method from os package in Golang to delete the files from a directory.

Also, read:

In this tutorial, we will explain how to delete a specific file from a directory and also delete all files from a directory using Golang.

Deleting Specific File

We can use the method Remove() to delete files from a directory. Here in below example code we will pass file path to delete file.

package main

import (
    "fmt"
    "os"
)

func main() {
    
    file := "C:/Go/bin/file/files/IMG_4322.jpg"
    
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("File delete successfully.")
	   
}

Deleting All Files from Directory

We will delete all files by reading all files from a directory. Here we will open the directory with os.Open() method and then read directory using Readdir method. Then we will loop through all files and delete one by one using os.Remove() method.

package main

import (
    "fmt"
    "os"
)

func main() {
    
    directory := "C:/Go/bin/file/files/"
    
    readDirectory, _ := os.Open(directory)
    allFiles, _ := readDirectory.Readdir(0)
    
    for f := range(allFiles) {
        file := allFiles[f]

        fileName := file.Name()
        filePath := directory + fileName
        
        os.Remove(filePath)
        fmt.Println("Deleted file:", filePath)
    }
}

The above example code will delete all files with following messages:

Deleted file: C:/Go/bin/file/files/IMG_4322.jpg
Deleted file: C:/Go/bin/file/files/IMG_4323.jpg
Deleted file: C:/Go/bin/file/files/IMG_4324.jpg
Deleted file: C:/Go/bin/file/files/IMG_4325.jpg

We can also delete all files from a directory using os.RemoveAll() default method. Here is the complete code to delete all files using os.RemoveAll() method.

package main

import (
    "fmt"
    "os"
)

func main() {
    
    directory := "C:/Go/bin/file/files/"
    
    err := os.RemoveAll(directory) 
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("All files deleted from directory.")
}

You may also like: