Cookies management by TermsFeed Cookie Consent

๐Ÿค Create a new file in Go

shorts introduction file

To create a new empty file in Go, use the os.Create() function.

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.


Thank you for being on our site ๐Ÿ˜Š. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

๐Ÿงน Delete or remove a file in Go

shorts introduction file

๐Ÿพ How to compare strings in Go

shorts introduction strings

๐Ÿ›‘ Exit an app in Go

shorts introduction os