Creating Directories
Single Directory
Create a single directory withos.Mkdir:
The second argument to
os.Mkdir is the permission mode (0755 means read/write/execute for owner, read/execute for others).Directory Hierarchy
Create a hierarchy of directories including parents withos.MkdirAll:
os.MkdirAll is similar to the command-line mkdir -p - it creates all necessary parent directories.Removing Directories
Clean Up After Use
Reading Directory Contents
Useos.ReadDir to list directory contents:
os.ReadDir returns a slice of os.DirEntry objects, which provide efficient access to file information.Changing Directory
Useos.Chdir to change the current working directory:
Walking Directory Trees
Usefilepath.WalkDir to recursively visit all files and directories:
The
visit function is called for every file and directory encountered, including the root directory.Complete Example
Common Operations
- Create
- List
- Remove
- Walk
Advanced Walking
Skip Directories
Filter by File Type
DirEntry vs FileInfo
os.DirEntry is more efficient than os.FileInfo for directory listings because it avoids unnecessary system calls.Best Practices
Use MkdirAll for safety
Use MkdirAll for safety
Prefer
os.MkdirAll over os.Mkdir when creating directories. It safely handles existing directories and creates parent directories as needed.Clean up temporary directories
Clean up temporary directories
Use
defer os.RemoveAll() to ensure temporary directories are cleaned up, even if errors occur.Check errors in walk functions
Check errors in walk functions
Always check and handle errors in
filepath.WalkDir callback functions. Return the error to stop walking or filepath.SkipDir to skip a directory.Use appropriate permissions
Use appropriate permissions
- 0755 for directories (rwxr-xr-x): owner can read/write/execute, others can read/execute
- 0700 for private directories (rwx------): only owner can access
Avoid Chdir in concurrent code
Avoid Chdir in concurrent code
os.Chdir affects the entire process. In concurrent programs, use absolute paths instead of changing directories.Use DirEntry efficiently
Use DirEntry efficiently
Call
entry.Info() only when you need full file information. Basic operations like Name() and IsDir() are more efficient.Directory Operations Reference
os.Mkdir
Create a single directory
os.MkdirAll
Create directory hierarchy with parents
os.Remove
Remove empty directory
os.RemoveAll
Remove directory and all contents
os.ReadDir
List directory contents
os.Chdir
Change current directory
filepath.WalkDir
Recursively walk directory tree
os.Getwd
Get current working directory
Related Topics
File Paths
Learn about portable file path operations
Temporary Files
Working with temporary files and directories