go言語 ファイル内のデータを1行ずつ取得する

  • 作成日 2021.05.25
  • 更新日 2022.10.31
  • go
go言語 ファイル内のデータを1行ずつ取得する

go言語で、ライブラリbufioのReadLineを使用して、ファイル内のデータを1行ずつ取得するサンプルコードを記述してます。go言語のバージョンは1.15.4を使用してます。

環境

  • OS windows10 pro 64bit
  • go言語 1.15.4

ReadLine使い方

ReadLineを使用すれば、データを1行ずつ取得することが可能です。

for {
	line, _, err := bu.ReadLine()
	if err == io.EOF {
		break
	}
	fmt.Printf("%s\n", line)
}

以下は、「sample.txt」内にあるデータを1行ずつ取得するサンプルコードとなります。

sample.txt

ソースコード

package main

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

func main() {

	name := "sample.txt"

	f, _ := os.Open(name)
	bu := bufio.NewReaderSize(f, 1024)

	for {
		line, _, err := bu.ReadLine()
		if err == io.EOF {
			break
		}
		fmt.Printf("%s\n", line)
	}

	// test
	// test
	// test

	// test
	// test

	f.Close()

}