【译文】go读取文件-逐行读取文件|Go主题月

459 阅读1分钟

【译文】

原文地址:golangbot.com/read-files/

逐行读取文件

在本节中,我们将讨论如何使用Go逐行读取文件。这可以使用bufio包来完成。

请更换的内容test.txt与以下

Hello World. Welcome to file handling in Go.  
This is the second line of the file.  
We have reached the end of the file.  

以下是逐行读取文件所涉及的步骤。

  1. 打开文件
  2. 从文件创建一个新的扫描
  3. 扫描文件并逐行读取。

更换的内容filehandling.go与以下

package main

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

func main() {  
    fptr := flag.String("fpath", "test.txt", "file path to read from")
    flag.Parse()

    f, err := os.Open(*fptr)
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
        log.Fatal(err)
    }
    }()
    s := bufio.NewScanner(f)
    for s.Scan() {
        fmt.Println(s.Text())
    }
    err = s.Err()
    if err != nil {
        log.Fatal(err)
    }
}

在上面程序的15行中,我们使用从命令行标志传递的路径打开文件。在行号 24,我们使用该文件创建一个新的扫描。scan()方法中第 25行将读取文件的下一行,并且所读取的字符串将通过该text()方法可用。

扫描返回后false,该Err()方法将返回扫描过程中发生的任何错误。如果错误是“ End of File”,Err()将返回nil

如果我们使用命令运行上面的程序:

cd ~/Documents/filehandling  
go install  
filehandling -fpath=/path-of-file/test.txt  

文件的内容将逐行打印,如下所示。

Hello World. Welcome to file handling in Go.  
This is the second line of the file.  
We have reached the end of the file.  

这使我们到了本教程的结尾。希望你喜欢。

前文回顾

【译文】go读取文件-将整个文件读入内存|Go主题月

【译文】go读取文件-小块读取文件|Go主题月