英文:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论