Writing to a File

· 193 words · 1 minute read

Often it’s very useful being able to write to a file from a program for logging purposes, saving results or as a data store. This is a little snippet on how to write text/data 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 using io.WriteString. 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). With a final file sync on close to prevent any un-caught errors (see this post for info).

package main

import (
    "io"
    "log"
    "os"
)

func main() {
    err := WriteToFile("result.txt", "Hello Readers of golangcode.com\n")
    if err != nil {
        log.Fatal(err)
    }
}

// WriteToFile will print any string of text to a file safely by
// checking for errors and syncing at the end.
func WriteToFile(filename string, data string) error {
    file, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer file.Close()

    _, err = io.WriteString(file, data)
    if err != nil {
        return err
    }
    return file.Sync()
}

Write Text to File in Go

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. He loves coding, but also enjoys cycling and camping in his spare time.

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!