Os.Remove. A directory may have many files in it. With os.Remove, we can remove just 1 file at a time. But it is possible to use a loop to remove all files in the directory.
With Readdir, we get a slice of all the files in a directory. We can then get the full paths of each file, and pass those to the os.Remove method. All files are deleted in the folder.
Example. To begin, we specify a target directory—you will want to adjust this to point to a location on your computer. Use a path syntax for your target platform.
Part 1 We first use os.Open to open the directory. We then use Readdir to get a slice containing all the files from the directory.
Part 2 We use a for-range loop over the files and then get each of their names with the Name() func.
Part 3 We get the full path by concatenating the directory with the file name, and then pass the path to os.Remove.
package main
import (
"fmt""os"
)
func main() {
// Part 1: open the directory and read all its files.
directory := "/home/sam/test/"
dirRead, _ := os.Open(directory)
dirFiles, _ := dirRead.Readdir(0)
// Part 2: loop over the directory's files.
for index := range(dirFiles) {
fileHere := dirFiles[index]
// Part 3: get name of file and its full path.
nameHere := fileHere.Name()
fullPath := directory + nameHere
os.Remove(fullPath)
fmt.Println("Removed file:", fullPath)
}
}Removed file: /home/sam/test/Untitled Document 3
Removed file: /home/sam/test/Untitled Document
Removed file: /home/sam/test/Untitled Document 2
Notes, results. You can see that there were 3 Untitled Documents that were removed when the program was executed. These were in the folder when I ran the Go program.
Notes, validation. Before deleting many files, it sometimes helps to have a confirmation, or some sort of logic test. It can be hard to recover from a mass deletion made in error.
Review. We can directly invoke os.Remove with a path argument to delete a file. And in a loop (one based on the result of Readdir) we can delete the entire contents of a directory.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 31, 2024 (edit).