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
+9.5k Golang : Eroding and dilating image with OpenCV example
+15.1k Golang : How to get Unix file descriptor for console and file
+5.3k Javascript : How to loop over and parse JSON data?
+12k Golang : md5 hash of a string
+11k Golang : Calculate Relative Strength Index(RSI) example
+10.9k Golang : Generate random elements without repetition or duplicate
+17.9k Golang : Put UTF8 text on OpenCV video capture image frame
+5.4k PHP : Fix Call to undefined function curl_init() error
+9.9k Golang : Identifying Golang HTTP client request
+7.9k Golang : Get all countries phone codes
+14.4k Golang : Overwrite previous output with count down timer