Home
Go
os.Remove: Delete All Files in Directory
This page was last reviewed on Dec 20, 2022.
Dot Net Perls
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.
Detail We first use os.Open to open the directory. We then use Readdir to get a slice containing all the files from the directory.
Detail We use a for-range loop over the files and then get each of their names with the Name() func.
for
Detail 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() { // 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.