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:
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:
For example, to remove a file from the current directory, we can do:
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:
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:
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!!