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
Find capacity of Channel, Pointer and Slice
How to find out element position in slice?
Convert Float32 to Float64 and Float64 to Float32
Golang Functions Returning Multiple Values
How to read current directory using Readdir?
Runtime package variables
Copy an array by value and reference into another array
How to kill execution of goroutine?
Subtract N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time.
Regular expression to extract all Non-Alphanumeric Characters from a String