Добавление к файлу в Go (Golang): методы и примеры

Чтобы добавить файл в Go (Golang), вы можете использовать несколько методов. Вот несколько примеров:

Метод 1: использование пакета osи структуры File:

package main
import (
    "fmt"
    "os"
)
func main() {
    fileName := "filename.txt"
    data := []byte("This is the new content to be appended.\n")
    // Open the file in append mode with write-only permission and file creation if it doesn't exist
    file, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()
    // Write the data to the file
    _, err = file.Write(data)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Data appended successfully.")
}

Метод 2: использование пакета osи структуры Fileс методом WriteString:

package main
import (
    "fmt"
    "os"
)
func main() {
    fileName := "filename.txt"
    data := "This is the new content to be appended.\n"
    // Open the file in append mode with write-only permission and file creation if it doesn't exist
    file, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()
    // Append the data to the file
    _, err = file.WriteString(data)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Data appended successfully.")
}

Способ 3: использование пакета ioutilи функции WriteFile:

package main
import (
    "fmt"
    "io/ioutil"
)
func main() {
    fileName := "filename.txt"
    data := []byte("This is the new content to be appended.\n")
    // Append the data to the file
    err := ioutil.WriteFile(fileName, data, 0644)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Data appended successfully.")
}