Golang : Find files by extension
This is a filepath.Ext()
function example and it will only display files with .png
extension in the current directory. You can adapt the code for other purposes.
findfilesbyextension.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" {
fmt.Println(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 files by extension
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
+3.8k Facebook : How to place save to Facebook button on your website
+6.9k Golang : Load DSA public key from file example
+8.3k Golang : Find correlation coefficient example
+4.5k Swift : Convert string array to array example
+9.9k Golang : Calculate Relative Strength Index(RSI) example
+7.4k Golang : Generate Datamatrix barcode
+15k Golang : Get IP addresses of a domain name
+6.5k Golang : Rename part of filename
+8.7k Golang : Bcrypting password
+16.7k Golang : Get all upper case or lower case characters from string example
+25.5k PHP : Convert(cast) string to bigInt
+12.1k Golang : Linear algebra and matrix calculation example