golang

Golang Delete File

It is no doubt that files are some of the important tools for programmers. For example, we can use files to read data or even store logs from our programs. This means that we need to perform operations such as creating and deleting files and directories.

This article will learn how to delete or remove files from the system using the Go programming language.

Golang OS Package

The OS package provides the functionality to remove a file in go. Hence we need to import it as shown in the snippet below:

import "os"

Once imported, we can use it.

Delete a Single File

To delete a single file, we use the Remove() method. The syntax is as shown:

os.Remove("path_to_file")

For example, to remove a file from the current directory, we can do:

packagemain
import (
    "log"
    "os"
)
funcmain() {
    err := os.Remove("hello.txt")
    if err != nil {
        log.Fatal(err)
    }
}

The above example deletes the file “hello.txt” from the current working directory.

If you want to remove a file outside of your current working directory, you can use the absolute path as shown in the example below:

package main
import (
    "log"
    "os"
    "path/filepath"
)
funcmain() {
    path := filepath.Join("dir1", "dir2", "filename.txt")
    err := os.Remove(path)
    if err != nil {
        log.Fatal(err)
    }
}

In the example above, we use the filepath.Join() method to create an absolute path to the file.

We then pass the filepath to the Remove() method.

Check our tutorial on Golang or join the path to learn more.

Delete Directory and Subdirectories

The os package also provides us with the RemoveAll() method. This takes a path to a directory and removes all the files and subdirectories inside it.

A sample code is as shown:

err := os.RemoveAll("path_to_directory")

if err != nil {

log.Fatal(err)

} else {

fmt.Println("Directory removed!")

}

The example above removes the directory in the specified path.

Conclusion

In this guide, you learned how to delete files and directories using the os package from the Go standard library.

Keep Coding!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list