To create a new file using the os
package in Golang, you can use the Create
function from os
module. Here is an example:
package main
import (
"fmt"
"os"
)
func main() {
// Create a new file named "example.txt"
file, err := os.Create("example.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
fmt.Println("File created successfully.")
}
In this example, the os.Create
function is used to create a new file named "example.txt". If any error occurs during the file creation, it will be captured in the err
variable.
Make sure to defer the Close
method on the file object to ensure it gets closed after use. The file.Close()
statement is executed just before the main
function exits.
After successfully running the program, a new file named "example.txt" will be created in the current directory.