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
Golang download image from given URL
How to use function from another file golang?
How to count number of repeating words in a given String?
How to check if a string contains a white space in Golang?
How to read names of all files and folders in current directory?
Example: ReadAll, ReadDir, and ReadFile from IO Package