Write a Text File in Golang

Here is a code of how to write a Text File in Golang. We separate the code in two steps. In the first, we verify that the file does not exist and create it. In the second, we write at least two lines of text and verify that there is no error.

ยป More Golang Examples

package main

import (
	"fmt"
	"os"
)

//geekole.com

var path = "textfile.txt"

func main() {
	createFile()
	writeFile()
	fmt.Println("Text File Created Successfully")
}
func createFile() {
	var _, err = os.Stat(path)
	if os.IsNotExist(err) {
		var file, err = os.Create(path)
		checkError(err)
		defer file.Close()
	}
}
func writeFile() {
	var file, err = os.OpenFile(path, os.O_RDWR, 0644)
	checkError(err)
	defer file.Close()
	_, err = file.WriteString("Hello \n")
	checkError(err)
	_, err = file.WriteString("World! \n")
	checkError(err)
	err = file.Sync()
	checkError(err)
}
func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

We create a function that first checks if the file exists and if not, creates it:

func createFile() {
	var _, err = os.Stat(path)

	if os.IsNotExist(err) {
		var file, err = os.Create(path)
		checkError(err)
		defer file.Close()
	}
}

After that, we create a second funtion that writes two lines of text with a “Hello” and a “World!”

At the end of the block we update our changes with the file.Sync() funtion.

func writeFile() {
	var file, err = os.OpenFile(path, os.O_RDWR, 0644)
	checkError(err)
	defer file.Close()

	_, err = file.WriteString("Hello \n")
	checkError(err)
	_, err = file.WriteString("World! \n")
	checkError(err)

	err = file.Sync()
	checkError(err)
}

And finally, we have a checkError function:

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

When you run the code, a new text file will be created.

Write a Text File in Golang

We hope this example of Write a Text File in Golang will help you.

Se more: https://decodigo.com/go-crear-archivo-de-texto