我找不到文件。围棋中的ReadLine函数。

如何一行一行地读取文件?


当前回答

import (
     "bufio"
     "os"
)

var (
    reader = bufio.NewReader(os.Stdin)
)

func ReadFromStdin() string{
    result, _ := reader.ReadString('\n')
    witl := result[:len(result)-1]
    return witl
}

下面是一个ReadFromStdin()函数的例子,它类似于fmt.Scan(&name),但它接受所有带空格的字符串,比如:"Hello My Name is…"

var name string = ReadFromStdin()

println(name)

其他回答

你也可以使用带\n的ReadString作为分隔符:

  f, err := os.Open(filename)
  if err != nil {
    fmt.Println("error opening file ", err)
    os.Exit(1)
  }
  defer f.Close()
  r := bufio.NewReader(f)
  for {
    path, err := r.ReadString(10) // 0x0A separator = newline
    if err == io.EOF {
      // do something here
      break
    } else if err != nil {
      return err // if you return error
    }
  }

扫描*功能是伟大的用户在这里。下面是go-lang docs中稍微修改过的单词扫描器示例,用于扫描文件中的行。

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {
    // An artificial input source.
    const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
    scanner := bufio.NewScanner(strings.NewReader(input))
    // Set the split function for the scanning operation.
    scanner.Split(bufio.ScanLines)
    // Count the lines.
    count := 0
    for scanner.Scan() {
        fmt.Println(scanner.Text())
        count++
    }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading input:", err)
    }
    fmt.Printf("%d\n", count)
}

在Go 1.16的新版本中,我们可以使用包嵌入来读取文件内容,如下所示。

package main

import _"embed"


func main() {
    //go:embed "hello.txt"
    var s string
    print(s)

    //go:embed "hello.txt"
    var b []byte
    print(string(b))

    //go:embed hello.txt
    var f embed.FS
    data, _ := f.ReadFile("hello.txt")
    print(string(data))
}

欲了解更多详情,请访问https://tip.golang.org/pkg/embed/ 和 https://golangtutorial.dev/tips/embed-files-in-go/

bufio.Reader.ReadLine()工作得很好。但是如果你想通过字符串读取每一行,尝试使用ReadString('\n')。它不需要重新发明轮子。

另一种方法是使用io/ioutil和strings库来读取整个文件的字节,将它们转换为字符串,并使用“\n”(换行符)字符作为分隔符来分割它们,例如:

import (
    "io/ioutil"
    "strings"
)

func main() {
    bytesRead, _ := ioutil.ReadFile("something.txt")
    fileContent := string(bytesRead)
    lines := strings.Split(fileContent, "\n")
}

从技术上讲,您不是逐行读取文件,但是您可以使用这种技术解析每一行。此方法适用于较小的文件。如果您试图解析一个大型文件,请使用逐行读取的技术之一。