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
How to set timeout for http.Get() requests in Golang?
How can we reverse a simple string in Go?
How to get the current date and time with timestamp in local and other timezones ?
Example: Stack and Caller from RUNTIME package
How to check if a string contains certain characters in Golang?
Convert Float32 to Float64 and Float64 to Float32