How to read/scan a .txt file in GO

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

How to read/scan a .txt file in GO

问题

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

  1. file, err := os.Open("file.txt")
  2. check(err)
  3. 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:

  1. file, err := os.Open("file.txt")
  2. check(err)
  3. 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

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "strings"
  7. )
  8. func main() {
  9. data, err := ioutil.ReadFile("/etc/passwd")
  10. if err != nil {
  11. log.Fatal(err)
  12. }
  13. lines := strings.Split(string(data), "\n")
  14. for _, line := range lines {
  15. fmt.Println("line:", string(line))
  16. }
  17. }
英文:

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

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "strings"
  7. )
  8. func main() {
  9. data, err := ioutil.ReadFile("/etc/passwd")
  10. if err != nil {
  11. log.Fatal(err)
  12. }
  13. lines := strings.Split(string(data), "\n")
  14. for _, line := range lines {
  15. fmt.Println("line:", string(line))
  16. }
  17. }

答案2

得分: 1

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

  1. for {
  2. line, err := r.ReadBytes('\n')
  3. if err != nil {
  4. break
  5. }
  6. myList = append(myList, string(line))
  7. }

这段代码的作用是循环读取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.

  1. for {
  2. line, err := r.ReadBytes('\n')
  3. if err != nil {
  4. break
  5. }
  6. myList = append(myList, string(line))
  7. }

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:

确定