LoginSignup
30
27

More than 5 years have passed since last update.

golangでテキストファイルを1行ずつ読んで配列(スライス)に詰め込む

Last updated at Posted at 2014-06-05
package main

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

func main() {
  lines := fromFile("hoge.txt")
  fmt.Printf("lines: %v\n", lines)
}

func fromFile(filePath string) []string {
  // ファイルを開く
  f, err := os.Open(filePath)
  if err != nil {
    fmt.Fprintf(os.Stderr, "File %s could not read: %v\n", filePath, err)
    os.Exit(1)
  }

  // 関数return時に閉じる
  defer f.Close()

  // Scannerで読み込む
  // lines := []string{}
  lines := make([]string, 0, 100)  // ある程度行数が事前に見積もれるようであれば、makeで初期capacityを指定して予めメモリを確保しておくことが望ましい
  scanner := bufio.NewScanner(f)
  for scanner.Scan() {
    // appendで追加
    lines = append(lines, scanner.Text())
  }
  if serr := scanner.Err(); serr != nil {
    fmt.Fprintf(os.Stderr, "File %s scan error: %v\n", filePath, err)
  }

  return lines
}

Memo

  • 改行区切りのテキストデータの読み込みはbufio.Scannerが便利なので使うべし
    • "Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text."
  • 空要素のスライスを用意し、appendで読み込んだ行内容を順次追加する
  • ファイルのクローズは関数return時に(確実に)行いたいのでdeferで呼ぶ。関数が長くなってreturnが複数箇所に存在するような場合に有用
    • defer指定処理が実行されるのはreturn時のみで、os.Exit(1)した場合は実行 されない ので注意
30
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
27