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
+26.2k Golang : Force your program to run with root permissions
+4.3k Golang : PGX CopyFrom to insert rows into Postgres database
+44k Golang : Use wildcard patterns with filepath.Glob() example
+6.1k Golang : Combine slices of complex numbers and operation example
+29.9k Golang : Remove characters from string example
+19.8k nginx: [emerg] unknown directive "passenger_enabled"
+11.8k Golang : Display list of countries and ISO codes
+19k Golang : Get current URL example
+33.5k Golang : Smarter Error Handling with strings.Contains()
+26.7k Golang : Convert CSV data to JSON format and save to file
+11.5k Golang : Clean formatting/indenting or pretty print JSON result
+6.7k Web : How to see your website from different countries?