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
+10.1k Golang : Text file editor (accept input from screen and save to file)
+16.4k Golang : Get IP addresses of a domain name
+23.1k Golang : Randomly pick an item from a slice/array example
+18.9k Golang : Read input from console line
+30.8k error: trying to remove "yum", which is protected
+11.2k Golang : Intercept and process UNIX signals example
+17.3k Golang : Check if IP address is version 4 or 6
+19.2k Golang : Delete item from slice based on index/key position
+17.2k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+79.8k Golang : How to return HTTP status code?
+10.5k Golang : Get local time and equivalent time in different time zone
+13.9k Golang : How to check if a file is hidden?