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 : How to get username from email address
+15.3k Golang : File path independent of Operating System
+23k Golang : Time slice or date sort and reverse sort example
+3.6k Chrome : How to block socketloop.com links in Google SERP?
+28.7k Golang : Generate random string
+8.1k Golang : Web(Javascript) to server-side websocket example
+17.8k Golang : Check if directory exist and create if does not exist
+4.1k Golang : Display packages names during compilation
+22.2k Golang : Check if element exist in map
+11k Golang : How to parse plain email text and process email header?
+4.5k Unix/Linux : How to find out the hard disk size?
+3.7k Linux : sudo yum updates not working