0
0
GoHow-ToBeginner · 3 min read

How to List Files in Directory in Go: Simple Guide

In Go, you can list files in a directory using the os.ReadDir function which returns a list of directory entries. You then loop through these entries to get file names or other info.
📐

Syntax

The main function to list files in a directory is os.ReadDir. It takes the directory path as a string and returns a slice of os.DirEntry and an error.

  • os.ReadDir(path string): Reads the directory named by path.
  • []os.DirEntry: A list of directory entries (files and folders).
  • DirEntry.Name(): Gets the name of the file or folder.
  • DirEntry.IsDir(): Checks if the entry is a directory.
go
entries, err := os.ReadDir("path/to/directory")
if err != nil {
    // handle error
}
for _, entry := range entries {
    fmt.Println(entry.Name())
}
💻

Example

This example shows how to list all files and folders in the current directory and print their names.

go
package main

import (
    "fmt"
    "os"
)

func main() {
    entries, err := os.ReadDir(".")
    if err != nil {
        fmt.Println("Error reading directory:", err)
        return
    }
    for _, entry := range entries {
        fmt.Println(entry.Name())
    }
}
Output
main.go README.md folder file.txt
⚠️

Common Pitfalls

One common mistake is not checking the error returned by os.ReadDir, which can cause your program to panic if the directory does not exist or is inaccessible.

Another is confusing files with directories; use entry.IsDir() to check if an entry is a folder.

go
package main

import (
    "fmt"
    "os"
)

func main() {
    // Wrong: ignoring error
    entries, _ := os.ReadDir("nonexistent")
    for _, entry := range entries {
        fmt.Println(entry.Name())
    }

    // Right: checking error
    entries, err := os.ReadDir("nonexistent")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    for _, entry := range entries {
        if !entry.IsDir() {
            fmt.Println("File:", entry.Name())
        }
    }
}
Output
Error: open nonexistent: no such file or directory
📊

Quick Reference

Function/MethodDescription
os.ReadDir(path string)Reads directory entries from the given path
DirEntry.Name()Returns the name of the file or directory
DirEntry.IsDir()Returns true if the entry is a directory
os.ReadDir errorAlways check for errors to avoid crashes

Key Takeaways

Use os.ReadDir to get a list of files and directories in a path.
Always check the error returned by os.ReadDir before using the results.
Use DirEntry.Name() to get the file or folder name.
Use DirEntry.IsDir() to distinguish files from directories.
Handle errors gracefully to avoid program crashes.