How to read/write from/to file in Golang?
In below program WriteString function used to write the content into the text file and ReadFile function is used to read the content from text file. The program will create test.txt file if not exist or truncate if already exist.
Golang read file line by line example:
Example
package main
import (
"io/ioutil"
"log"
"fmt"
"os"
)
func CreateFile() {
file, err := os.Create("test.txt") // Truncates if file already exists, be careful!
if err != nil {
log.Fatalf("failed creating file: %s", err)
}
defer file.Close() // Make sure to close the file when you're done
len, err := file.WriteString("The Go Programming Language, also commonly referred to as Golang, is a general-purpose programming language, developed by a team at Google.")
if err != nil {
log.Fatalf("failed writing to file: %s", err)
}
fmt.Printf("\nLength: %d bytes", len)
fmt.Printf("\nFile Name: %s", file.Name())
}
func ReadFile() {
data, err := ioutil.ReadFile("test.txt")
if err != nil {
log.Panicf("failed reading data from file: %s", err)
}
fmt.Printf("\nLength: %d bytes", len(data))
fmt.Printf("\nData: %s", data)
fmt.Printf("\nError: %v", err)
}
func main() {
fmt.Printf("########Create a file and Write the content #########\n")
CreateFile()
fmt.Printf("\n\n########Read file #########\n")
ReadFile()
}
Output
########Create a file and Write the content #########
Length: 139 bytes
File Name: test.txt
########Read file #########
Length: 139 bytes
Data: The Go Programming Language, also commonly referred to as Golang, is a general-purpose programming language, developed by a team at Goog
le.
Error:
Most Helpful This Week
Different ways to validate JSON string
How to check if a string contains a numbers in Golang?
Simple example of Map initialization in Go
Regular expression to extract text between square brackets
How to replace emoji characters in string using regex in Golang?
How to use function from another file golang?
How to use array in Go Programming Language?
How to check if a string contains only letters in Golang?
Split URL and Get Parameters from URL
Golang Read Write Create and Delete text file