Writing to a File

· 123 words · 1 minute read

Often it’s very useful being able to write to a file from a script, for logging purposes, saving results or as a data store. This is a little snippet on how to write to a file.

We use the os package to create the file, exiting the program and logging if it can’t do this and printing a string into the file with Fprintf. We’re also using defer to close the file access once the function has finished running (which is a really neat way of remembering to close files).

package main

import (

func main() {
    file, err := os.Create("result.txt")
    if err != nil {
        log.Fatal("Cannot create file", err)
    defer file.Close()

    fmt.Fprintf(file, "Hello Readers of golangcode.com")
Image of Author Edd Turtle

Author: Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below. Thanks for reading!