Golang : Read directory content with os.Open
There are few ways to traverse a directory tree and content in Go. One of them is os.File.Readdir function. In this tutorial, we will see how to read a directory and display its files and size. This example will use the os.Open http://golang.org/pkg/os/#File.Readdir function.
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() {
fmt.Println(file.Name(), file.Size(), "bytes")
}
}
}
Test this code out and see the output of your directory. Hope this tutorial is helpful.
See also : Golang : Read directory content with filepath.Walk()
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.8k Android Studio : AlertDialog to get user attention example
+7.1k Default cipher that OpenSSL used to encrypt a PEM file
+8.2k Golang : Trim everything onward after a word
+23.3k Golang : Randomly pick an item from a slice/array example
+6.6k CodeIgniter : form input set_value cause " to become & quot
+7.8k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+8.1k Javascript : How to check a browser's Do Not Track status?
+6.3k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+8.9k Golang : Gorilla web tool kit schema example
+26.7k Golang : Convert(cast) string to uint8 type and back to string
+8.6k Golang : Convert word to its plural form example