Directory operations
suggest changeCreate directory
dir := "my_dir"
err := os.Mkdir(dir, 0755)
if err != nil {
fmt.Printf("os.Mkdir('%s') failed with '%s'\n", dir, err)
}
dir := filepath.Join("topdir", "subdir")
err := os.MkdirAll(dir, 0755)
if err != nil {
fmt.Printf("os.MkdirAll('%s') failed with '%s'\n", dir, err)
}
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.
0755 is an octal permission mode. The leading 0 makes the literal octal, so each digit is in the range 0–7.
7is the owner's permissions:4(read) +2(write) +1(search/traverse).- the first
5is the group's permissions: read and traverse, not write. - the last
5is everyone else's permissions: read and traverse.
Delete directory
dir := "my_dir"
err := os.Remove(dir)
if err != nil {
fmt.Printf("os.Remove('%s') failed with '%s'\n", dir, err)
}
os.Remove removes a file or an empty directory. It fails if the directory still contains files or subdirectories.
dir := "my_dir"
err := os.RemoveAll(dir)
if err != nil {
fmt.Printf("os.RemoveAll('%s') failed with '%s'\n", dir, 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 os.ReadDir:
func main() {
dir := "."
fileInfos, err := os.ReadDir(dir)
if err != nil {
log.Fatalf("os.ReadDir('%s') failed with '%s'\n", dir, err)
}
for i, fi := range fileInfos {
if i < 4 {
info, err := fi.Info()
if err != nil {
log.Printf("reading information for %q failed: %v", fi.Name(), err)
continue
}
fmt.Printf("Path: %s, is dir: %v, size: %d bytes\n", fi.Name(), fi.IsDir(), info.Size())
}
}
}
Path: app, is dir: false, size: 2206428 bytes
Path: go.mod, is dir: false, size: 21 bytes
Path: main.go, is dir: false, size: 400 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: 0 bytes
Path: app, is dir: false, size: 2179446 bytes
Path: go.mod, is dir: false, size: 21 bytes
Path: main.go, is dir: false, size: 466 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.
Return a non-nil error from the callback to stop the walk. filepath.SkipDir is the exception: it skips the rest of the current directory and the walk continues.