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
+7k Golang : A simple forex opportunities scanner
+10.1k Golang : Check a web page existence with HEAD request example
+29.8k Golang : How to get HTTP request header information?
+13.4k Golang : Read XML elements data with xml.CharData example
+12.6k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+8.5k Linux/Unix : fatal: the Postfix mail system is already running
+19.1k Golang : Calculate entire request body length during run time
+24.4k Golang : Time slice or date sort and reverse sort example
+14.1k Elastic Search : Mapping date format and sort by date
+13.9k Golang : concatenate(combine) strings
+9.5k Golang : How to extract video or image files from html source code
+10.6k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example