【译文】go读取文件 |
您所在的位置:网站首页 › golang逐行读取文件 › 【译文】go读取文件 |
【译文】 原文地址: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. 复制代码以下是逐行读取文件所涉及的步骤。 打开文件 从文件创建一个新的扫描 扫描文件并逐行读取。更换的内容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主题月 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |