Golang : Delete files by extension
Being able to select certain type of files to delete can be useful. In this follow up tutorial from Golang : Delete file, we are going to refine it further by only deleting files with certain extension with filepath.Ext()
function.
In our case, it will files with .png
extension.
Adapting the codes from earlier tutorial, we will add one additional if
statement into the code to only delete files with .png
extension.
The extra line is if filepath.Ext(file.Name()) == ".png"
deletefilebyextension.go
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
dirname := "." + string(filepath.Separator)
d, err := os.Open(dirname)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer d.Close()
files, err := d.Readdir(-1)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Reading "+ dirname)
for _, file := range files {
if file.Mode().IsRegular() {
if filepath.Ext(file.Name()) == ".png" {
os.Remove("file.Name()")
fmt.Println("Deleted ", file.Name())
}
}
}
}
Put couple of .png
files into the same directory as this go program and try it out.
Reference :
http://stackoverflow.com/questions/20115327/golang-rename-the-directory-and-partial-file-renaming
See also : Golang : Delete file
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.7k Golang : Setting variable value with ldflags
+20.9k Golang : How to get time zone and load different time zone?
+29.9k Golang : How to verify uploaded file is image or allowed file types
+21.1k Golang : Encrypt and decrypt data with TripleDES
+10.6k Golang : Sieve of Eratosthenes algorithm
+8.5k Golang : Accept any number of function arguments with three dots(...)
+9.1k Golang : How to protect your source code from client, hosting company or hacker?
+8.7k Golang : Get SPF and DMARC from email headers to fight spam
+8.4k Golang : How to join strings?
+22.2k Generate checksum for a file in Go
+11.5k Golang : convert(cast) float to string
+7k Golang : How to detect if a sentence ends with a punctuation?