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
+7.7k Golang : Identifying Golang HTTP client request
+16.6k Golang : Check if os.Stdin input data is piped or from terminal
+3.7k Golang *File points to a file or directory ?
+14k Golang : read gzipped http response
+8.4k Golang : Convert file unix timestamp to UTC time example
+5.4k Golang : Normalize email to prevent multiple signups example
+19.6k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+19.7k Golang : Fix type interface{} has no field or no methods and type assertions example
+7.8k Golang : interface - when and where to use examples
+11.4k Golang : Verify token from Google Authenticator App
+5.4k Golang : constant 20013 overflows byte error message
+5.5k Golang : Lock executable to a specific machine with unique hash of the machine