SoFunction
Updated on 2025-03-05

golang How to get the file list below the folder

One of the easier methods to find in golang's documentation is that there is a problem with this method that it will automatically recursively traverse the subdirectories of the current directory. In fact, we usually just want to get a list of files under a directory, and do not require so much information. At the same time, the code of this method is written more and more complicated, so we don't need to do this.

If you just want to get a list of files and folders under a directory, there are two simpler methods

ReadDir method using ioutil

package main 
import (
    "fmt"
    "io/ioutil"
)
 
func main() {
    files, _ := ("./")
    for _, f := range files {
            (())
    }
}

Glob method using filepath

package main  
import (
    "fmt"
    "path/filepath"
)
 
func main() {
    files, _ := ("*")
    (files) // contains a list of all files in the current directory
}

Supplement: golang gets the size of the file/directory (including the following files)

Look at the code ~

func DirSize(path string) (int64, error) {
 var size int64
 err := (path, func(_ string, info , err error) error {
  if !() {
   size += ()
  }
  return err
 })
 return size, err
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.