To create a new empty file in Go, use the os.Create()
function.
- It creates a new file if it does not exist, with the file mode 0666, for reading and writing.
- It truncates the file if it exists, which means that the contents of the file are removed without deleting the file.
- The returned file descriptor is open for reading and writing.
- If there is some problem, the function returns an error of type
*os.PathError
.
package main
import (
"fmt"
"log"
"os"
)
func main() {
f, err := os.Create("testFile.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
fmt.Println(f.Name())
}
Always remember to close the open file descriptor when you finish working with the file so that the system can reuse it:
defer f.Close()
You can then write data to this file. See how to do this in one of our previous tutorials here.