LoginSignup
16
14

More than 5 years have passed since last update.

Goでファイルの内容を1行ずつ読み込む

Posted at

Goでファイルの内容を1行ずつ読み込むときは、bufioを使います。

package main

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

func main() {
    filename := "file.txt"

    // ファイルオープン
    fp, err := os.Open(filename)
    if err != nil {
        // エラー処理
    }
    defer fp.Close()

    scanner := bufio.NewScanner(fp)

    for scanner.Scan() {
        // ここで一行ずつ処理
        fmt.Println(scanner.Text())
    }

    if err = scanner.Err(); err != nil {
        // エラー処理
    }
}

1行ずつ読む必要がない場合は、io/ioutilを使うことで簡単に読み込むことができます。

package main

import (
    "io/ioutil"
    "fmt"
)

func main() {
    filename := "file.txt"

    text, err := ioutil.ReadFile(filename)
    if err != nil {
        // エラー処理
    }

    // ReadFileの返り値は[]byte型なので注意
    fmt.Println(string(text))
}
16
14
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
16
14