Home > Backend Development > Golang > How to Append Text to a File in Go?

How to Append Text to a File in Go?

Linda Hamilton
Release: 2025-01-03 07:29:42
Original
597 people have browsed it

How to Append Text to a File in Go?

Appending to a File in Go

To write to a file in Go, you can use the ioutil.WriteFile function. However, if you want to append to a file, this function cannot be used. Instead, you can leverage the os.OpenFile function with the os.O_APPEND flag.

Here's how to append to a file in Go:

import (
    "fmt"
    "os"
)

func main() {
    filename := "myfile.txt"
    text := "New text to be appended\n"

    f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
    if err != nil {
        fmt.Println(err)
        return
    }

    defer f.Close()

    if _, err = f.WriteString(text); err != nil {
        fmt.Println(err)
        return
    }
}
Copy after login

In this code:

  • We open the file with the O_APPEND flag, which ensures that new data will be appended at the end of the existing file.
  • We also set the O_WRONLY flag to indicate that we will only be writing to the file.
  • We set the O_CREATE flag to indicate that the file should be created if it doesn't exist.
  • We use the f.WriteString method to append the provided text to the end of the file.
  • Remember to defer closing the file after the operation is complete.

The above is the detailed content of How to Append Text to a File in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template