Writing Files in Go

Go: Writing Files

In Go, writing files can be achieved using the os package, which provides various functions to create, open, write and close files.

How to write to a file in Go:


    package main

    import (
        "fmt"
        "os"
    )

    func main() {
        // Create or open the file
        file, err := os.Create("example.txt")
        if err != nil {
            fmt.Println("Error creating file:", err)
            return
        }
        defer file.Close() // Close the file when done

        // Write some data to the file
        _, err = file.WriteString("Hello, World!")
        if err != nil {
            fmt.Println("Error writing to file:", err)
            return
        }
    }

Explaination:

  • we first create a file called example.txt using the os.Create function. We check if an error occurred during the file creation process, and if so, we return and print the error message.

  • After creating the file, we defer its closing to ensure it gets closed once we're done writing to it.

  • Finally, we write the string "Hello, World!" to the file using the file.WriteString function. Again, we check if an error occurred during the writing process, and if so, we return and print the error message.

Previous Article

Next Article