How to read/scan a .txt file in GO

huangapple go评论75阅读模式
英文:

How to read/scan a .txt file in GO

问题

.txt文件有很多行,每行包含一个单词。所以我打开文件并将其传递给读取器:

file, err := os.Open("file.txt")
check(err)
reader := bufio.NewReader(file)

现在我想将每一行存储在一个字符串切片中。我相信我需要使用ReadBytes、ReadString、ReadLine或其中一个Scan函数。对于如何实现这一点,我希望能得到一些建议。谢谢。

英文:

The .txt file has many lines which each contain a single word. So I open the file and pass it to the reader:

file, err := os.Open("file.txt")
check(err)
reader := bufio.NewReader(file)

Now I want to store each line in a slice of strings. I believe I need to use ReadBytes, ReadString, ReadLine, or on of the Scan functions. Any advice on how to implement this would be appreciated. Thanks.

答案1

得分: 3

你可以使用ioutil.ReadFile()将所有行读入一个字节切片,然后在结果上调用split

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"strings"
)

func main() {
	data, err := ioutil.ReadFile("/etc/passwd")
	if err != nil {
		log.Fatal(err)
	}
	lines := strings.Split(string(data), "\n")

	for _, line := range lines {
		fmt.Println("line:", string(line))
	}
}
英文:

You can use ioutil.ReadFile() to read all lines into a byte slice and then call split on the result:

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"strings"
)

func main() {
	data, err := ioutil.ReadFile("/etc/passwd")
	if err != nil {
		log.Fatal(err)
	}
	lines := strings.Split(string(data), "\n")

	for _, line := range lines {
		fmt.Println("line:", string(line))
	}
}

答案2

得分: 1

r作为*bufio.Reader的实例,myList作为字符串切片,那么可以通过循环读取行直到行尾。

for {
    line, err := r.ReadBytes('\n')
    if err != nil {
        break
    }
    myList = append(myList, string(line))
}

这段代码的作用是循环读取r中的每一行,并将其添加到myList中,直到遇到行尾或发生错误。

英文:

Having r as an instance of *bufio.Reader, and myList as a slice of strings, than one could just loop and read lines till EOL.

   for {
        line, err := r.ReadBytes('\n')
        if err != nil {
            break
        }
        myList = append(myList, string(line))
   }

huangapple
  • 本文由 发表于 2013年9月24日 09:39:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/18971649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定