C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Open, Readdir: We first use os.Open to open the directory. We then use Readdir to get a slice containing all the files from the directory.
For: We use a for-range loop over the files and then get each of their names with the Name() func.
ForRemove: We get the full path by concatenating the directory with the file name, and then pass the path to os.Remove.
Golang program that uses os.Remove, deletes all files
package main
import (
"fmt"
"os"
)
func main() {
// The target directory.
directory := "/home/sam/test/"
// Open the directory and read all its files.
dirRead, _ := os.Open(directory)
dirFiles, _ := dirRead.Readdir(0)
// Loop over the directory's files.
for index := range(dirFiles) {
fileHere := dirFiles[index]
// Get name of file and its full path.
nameHere := fileHere.Name()
fullPath := directory + nameHere
// Remove the file.
os.Remove(fullPath)
fmt.Println("Removed file:", fullPath)
}
}
Output
Removed file: /home/sam/test/Untitled Document 3
Removed file: /home/sam/test/Untitled Document
Removed file: /home/sam/test/Untitled Document 2