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
+6.8k Golang : Detect sample rate, channels or latency with PortAudio
+33.5k Golang : Integer is between a range
+11k Golang : Detect user location with HTML5 geo-location
+7.3k Golang : Variadic function arguments sanity check example
+7.9k Golang : Executing and evaluating nested loop in html template
+24.9k Golang : Get executable name behind process ID example
+5.3k Golang : Dealing with backquote
+29.5k Golang : How to redirect to new page with net/http?
+5.1k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+7k Golang : Reverse a string with unicode
+9.7k Golang : Select region of interest with mouse click and crop from image