os.Open() / Create() / Remove()
These are the basic functions of the os package for opening, creating, and deleting files. They provide low-level file operations, making it straightforward to read, write, and remove files.
Syntax
// Open a file (read-only)
f, err := os.Open("file path")
// Create or overwrite a file (for writing)
f, err := os.Create("file path")
// Open a file with specific flags and permissions
f, err := os.OpenFile("file path", os.O_RDWR|os.O_CREATE, 0644)
// Delete a file
err := os.Remove("file path")
// Close a file (always call with defer)
defer f.Close()
Function List
| Function | Description |
|---|---|
| os.Open(name) | Opens a file in read-only mode. Returns an error if the file does not exist. |
| os.Create(name) | Creates a new file. If the file already exists, it truncates the contents and overwrites it. |
| os.OpenFile(name, flag, perm) | Opens a file with the specified flags and permissions. Allows fine-grained control such as read-write mode or append mode. |
| os.Remove(name) | Deletes a file or an empty directory. |
| f.Close() | Closes the file. Every opened file must be closed when you are done with it. |
Sample Code
package main
import (
"fmt"
"os"
)
func main() {
// Create a new file and write a string to it
f, err := os.Create("hello.txt")
if err != nil {
fmt.Println("Create error:", err)
return
}
defer f.Close()
f.WriteString("Hello, Go!\n")
fmt.Println("Created hello.txt")
// Open the file in read-only mode
r, err := os.Open("hello.txt")
if err != nil {
fmt.Println("Open error:", err)
return
}
defer r.Close()
// Read the contents
buf := make([]byte, 64)
n, _ := r.Read(buf)
fmt.Printf("Read content: %s", buf[:n])
// Delete the file
err = os.Remove("hello.txt")
if err != nil {
fmt.Println("Remove error:", err)
return
}
fmt.Println("Deleted hello.txt")
}
Notes
os.Open() is a shortcut for read-only access, and os.Create() is a shortcut for write access. When you need finer control, use os.OpenFile() and combine flags such as os.O_RDWR (read-write) and os.O_APPEND (append).
Always call defer f.Close() after opening a file to release the resource.Forgetting to call Close() leaks a file descriptor, which can cause problems in long-running programs. For reading or writing an entire file at once, os.ReadFile() / WriteFile() is more convenient.
If you find any errors or copyright issues, please contact us.