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
+12k Golang : Decompress zlib file example
+22.8k Golang : simulate tail -f or read last line from log file example
+18.1k Golang : Put UTF8 text on OpenCV video capture image frame
+8k Golang : Multiplexer with net/http and map
+11k Golang : Fix go.exe is not compatible with the version of Windows you're running
+30.3k Golang : How to verify uploaded file is image or allowed file types
+10.2k Golang : Use regular expression to get all upper case or lower case characters example
+10.8k Golang : Sieve of Eratosthenes algorithm
+38k Golang : Read a text file and replace certain words
+35.9k Golang : Get file last modified date and time
+11.5k Swift : Convert (cast) Float to String
+6.8k How to let Facebook Login button redirect to a particular URL ?