Essential Go File I/O  Edit on GitHub      File Issue

Directory operations

Create directory

dir := "my_dir"
err := os.Mkdir(dir, 0755)
if err != nil {
    fmt.Printf("os.Mkdir('%s') failed with '%s'\n", dir)
}
dir := filepath.Join("topdir", "subdir")
err := os.MkdirAll(dir, 0755)
if err != nil {
    fmt.Printf("os.MkdirAll('%s') failed with '%s'\n", dir)
}

os.Mkdir only succeeds if parent directory of dir already exists.

os.MkdirAll will create all intermediary directories.

0755 describes permissions for the directory.

Those are Unix style permissions in octal format.

Let’s deconstruct parts of 0755

Delete directory

dir := "my_dir"
err := os.Remove(dir)
if err != nil {
    fmt.Printf("os.Remove('%s') failed with '%s'\n", path, err)
}

os.Remove only works for empty directories i.e. directories without any files of sub-directories.

dir := "my_dir"
err := os.RemoveAll(dir)
if err != nil {
    fmt.Printf("os.RemoveAll('%s') failed with '%s'\n", path, err)
}

os.RemoveAll removes the directory and all its children (files and sub-directories).

List files in a directory

To list files and directories in a given directory we can use ioutil.ReadDir:

func main() {
	dir := "."
	fileInfos, err := ioutil.ReadDir(dir)
	if err != nil {
		log.Fatalf("ioutil.ReadDir('%s') failed with '%s'\n", dir, err)
	}
	for i, fi := range fileInfos {
		if i < 4 {
			fmt.Printf("Path: %s, is dir: %v, size: %d bytes\n", fi.Name(), fi.IsDir(), fi.Size())
		}
	}
}
Path: 000-index.md, is dir: false, size: 210 bytes
Path: 010-reading-files.md, is dir: false, size: 753 bytes
Path: 020-writing-files.md, is dir: false, size: 2913 bytes
Path: 030-file-operations.md, is dir: false, size: 2583 bytes

List files recursively

func main() {
	nShown := 0
	err := filepath.Walk(".", func(path string, fi os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if nShown > 4 {
			return nil
		}
		nShown++
		fmt.Printf("Path: %s, is dir: %v, size: %d bytes\n", fi.Name(), fi.IsDir(), fi.Size())
		return nil
	})

	if err != nil {
		fmt.Printf("filepath.Walk failed with '%s'\n", err)
	}
}
Path: ., is dir: true, size: 640 bytes
Path: 000-index.md, is dir: false, size: 210 bytes
Path: 010-reading-files.md, is dir: false, size: 753 bytes
Path: 020-writing-files.md, is dir: false, size: 2913 bytes
Path: 030-file-operations.md, is dir: false, size: 2583 bytes

To visit files in a directory recursively use filepath.Walk.

You provide a callback function that will be called for every file and directory under directory.

Callback function is called even for files/directories that we can’t read e.g. due to insufficient permissions.

We can end traversal early by returning non-nil error from callback function.

  ↑ ↓ to navigate     ↵ to select     Esc to close