Go Cheatsheet - Read & Write File

·

1 min read

Read & Write File

Read File content

1, Use ioutil.ReadFile:

content, err := ioutil.ReadFile("sample.txt")

2, Open file first (in read-only mode), then ioutil.ReadAll

f, err := os.Open("./main.go")
//or open in a different mode: 
// f, err := os.OpenFile("./main.go", os.O_RDWR, os.ModePerm)
content, err := ioutil.ReadAll(f)

3, Open file first, then read line by line

Use bufio.NewScanner:

sc := bufio.NewScanner(f)
for sc.Scan() {
    fmt.Println(sc.Text())
}

Use bufio.NewReader:

rd := bufio.NewReader(f)
for {
    ln, err := rd.ReadString('\n')
    if err != nil {
        if err == io.EOF {
            break
        }
        log.Fatalln("Failed to read file", err)
    }
    fmt.Print(ln)
}

Write to File

1, Dump whole content to a file:

ioutil.WriteFile("outf.txt", []byte("hello world"), os.ModePerm)

2, Create a new file then write (existing content will be truncated)

outf, err := os.Create("outf.txt")
defer outf.Close()
if err != nil {
    log.Fatalln("Failed to create file.", err)
}
outf.WriteString("hello world\n")

3, Append content to file:

outf, err = os.OpenFile(
    "outf.txt",
    os.O_WRONLY|os.O_APPEND|os.O_CREATE, // open file in append mode
    os.ModePerm,
)
defer outf.Close()
if err != nil {
    log.Fatalln("Failed to open file", err)
}
outf.WriteString("append line\n")