Home
Search
Golang os.Remove: Delete All Files in DirectoryUse the os.Remove method with Readdir to delete all the files in a directory.
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.
File
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.
Readdir
An 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.
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.
For
Remove 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) } }
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 Golang 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.
A 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.
Home
© 2007-2021 sam allen. see site info on the changelog