In this example, we will show you how to write to file in Go with an example.
The File.WriteString function writes the contents of a string to a file.
Go - write to file with File.WriteString
The example writes a string to a text file.
Let's first create an empty 'sample.txt' file that we want to write upon.
Let's create a file named go_example.go and add the following content to it:
package main
import (
"fmt"
"log"
"os"
)
func main() {
f, err := os.Create("sample.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
_, err2 := f.WriteString("My first fav programming languge is Go Lang \nMy second fav programming languge is Java \nMy third fav programming languge is Python\n")
if err2 != nil {
log.Fatal(err2)
}
fmt.Println("done")
}
Output:
G:\GoLang\examples>go run go_example.go done
After executing above program, open the 'sample.txt' file and you should able to see the content of the file as below:
My first fav programming languge is Go Lang My second fav programming languge is Java My third fav programming languge is Python
Comments
Post a Comment