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.
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.
os.Open
to open the directory. We then use Readdir
to get a slice containing all the files from the directory.for-range
loop over the files and then get each of their names with the Name()
func
.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
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.
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.
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.