To create a brand new empty file in Go, use the os.Create()
operate.
- It creates a brand new file if it doesn’t exist, with the file mode 0666, for studying and writing.
- It truncates the file if it exists, which signifies that the contents of the file are eliminated with out deleting the file.
- The returned file descriptor is open for studying and writing.
- If there may be some drawback, the operate returns an error of sort
*os.PathError
.
package deal important
import (
"fmt"
"log"
"os"
)
func important() {
f, err := os.Create("testFile.txt")
if err != nil {
log.Deadly(err)
}
defer f.Shut()
fmt.Println(f.Title())
}
At all times bear in mind to shut the open file descriptor whenever you end working with the file in order that the system can reuse it:
You possibly can then write information to this file. See how to do that in one among our earlier tutorials right here.