Introduction
In this challenge, you will learn how to work with directories in Go. Go provides several useful functions for working with directories in the file system.
This tutorial is from open-source community. Access the source code
In this challenge, you will learn how to work with directories in Go. Go provides several useful functions for working with directories in the file system.
Create a Go program that creates a new sub-directory in the current working directory, creates a hierarchy of directories, including parents, lists directory contents, changes the current working directory, and visits a directory recursively.
defer
their removal. os.RemoveAll
will delete a whole directory tree (similarly to rm -rf
).MkdirAll
. This is similar to the command-line mkdir -p
.ReadDir
lists directory contents, returning a slice of os.DirEntry
objects.Chdir
lets us change the current working directory, similarly to cd
.Walk
accepts a callback function to handle every file or directory visited.$ go run directories.go
Listing subdir/parent
child true
file2 false
file3 false
Listing subdir/parent/child
file4 false
Visiting subdir
subdir true
subdir/file1 false
subdir/parent true
subdir/parent/child true
subdir/parent/child/file4 false
subdir/parent/file2 false
subdir/parent/file3 false
In this challenge, you learned how to work with directories in Go. You learned how to create a new sub-directory, create a hierarchy of directories, list directory contents, change the current working directory, and visit a directory recursively.