1. 程式人生 > 其它 >go 逐行讀取檔案

go 逐行讀取檔案

前言

檔案 I/O,特別是對檔案的讀寫是程式語言中重要的功能。通常,我們需要逐行讀取檔案。

GO 提供了 bufio 軟體包,實現了有緩衝的 I/O。它包裝一個 io.Readerio.Writer 介面物件,建立另一個也實現了該介面,且同時還提供了緩衝和一些文字 I/O 的幫助函式的物件。

在讀取檔案之前,我們首先需要使用 os.Open() 函式將其開啟,該函式返回指向檔案的指標型別。程式碼段中顯示的 D:\\go_work\\test.txt 檔案需要已經存在在系統中(將路徑放置到檔案所在的位置)。

bufio.NewScanner(file) 函式建立並返回一個從 r 讀取資料的 Scanner

型別,該型別中的函式支援讀取檔案,其中預設的分割函式是 ScanLines

要逐行讀取檔案,我們需要使用兩種在新的 Scanner 的方法 Scan,它會獲取當前位置的 token(該 token 可以通過 Bytes 或 Text 方法獲得,在本例中為新行),並讓 Scanner 的掃描位置移動到下一個 token,和 Text(或 Byte)讀取呼叫 Scan 時生成的最新符記。

如果在讀取檔案時遇到任何錯誤,可以通過在新的 Scanner 上呼叫 Err() 方法來處理這些錯誤,該方法將返回 Scanner 遇到的第一個非檔案結尾錯誤;除非是 io.EOF,此時 Err 會返回 nil

Go 逐行讀取檔案的完整程式碼

package main

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

func main() {
	// open the file
	file, err := os.Open("D:\\go_work\\test.txt")

	// handle errors while opening
	if err != nil {
		log.Fatalf("Error when opening file: %s", err)
	}
	defer file.Close()

	fileScanner := bufio.NewScanner(file)

	// read line by line
	for fileScanner.Scan() {
		fmt.Println(fileScanner.Text())
	}
	// handle first encountered error while reading
	if err := fileScanner.Err(); err != nil {
		log.Fatalf("Error while reading file: %s", err)
	}
}

配置 Scanner 行為

Scanner 型別具有 Split 函式,該函式接受 SplitFunc 函式來確定 Scanner 如何拆分給定的位元組片。預設的 SplitFuncScanLines,它將返回文字的每一行,並刪除行尾標記。

例如,我們可以使用單詞進行拆分,如下面的程式碼片段所示:

scanner.Split(bufio.ScanWords)  //configure how the scanner behaves