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
+35k Golang : Convert date or time stamp from string to time.Time type
+12.2k Golang : Verify token from Google Authenticator App
+4.8k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+7k Golang : Reverse text lines or flip line order example
+28.6k Golang : Remove characters from string example
+4.4k Golang : Reclaim memory occupied by make() example
+4.6k PHP : Convert CSV to JSON with YQL example
+5.2k Golang : Map within a map example
+5.5k Golang : Totalize or add-up an array or slice example
+27.8k Golang : JQuery AJAX post data to server and send data back to client example
+3.5k Adding Skype actions such as call and chat into web page examples
+20.4k Golang : Use TLS version 1.2 and enforce server security configuration over client