Go

[Go] File handling

llHoYall 2020. 12. 2. 19:34

File Creating

file, err := os.Open(filename)
if err != nil {
  log.Fatal(err)
}

File Reading

scanner := bufio.NewScanner(file)
for scanner.Scan() {
  fmt.Println(scanner.Text())
}

Scan() method reads one line from the file.

Text() method returns the content of the line as a string.

File Closing

err = file.Close()
if err != nil {
  log.Fatal(err)
}

Example

package main

import (
  "bufio"
  "fmt"
  "log"
  "os"
)

func main() {
  file, err := os.Open("../README.md")
  if err != nil {
    log.Fatal(err)
  }
  
  scanner := bufio.NewScanner(file)
  for scanner.Scan() {
    fmt.Println(scanner.Text())
  }
  
  err = file.Close()
  if err != nil {
    log.Fatal(err)
  }
  
  if scanner.Err() != nil {
    log.Fatal(scanner.Err())
  }
}

Err() method indicates whether an error occurred while reading the contents of the file.

반응형