3 回答
TA贡献1811条经验 获得超6个赞
这是执行相同操作的另一种方法,使用bufio.Reader. 逻辑几乎与Elwiner的回答相似。
myReadLine下面的函数bufio.Reader用于读取文件中的下一个多行条目。
func myReadLine(file *os.File, reader *bufio.Reader) (lines []string, err error){
for {
line, _, err := reader.ReadLine()
if err != nil || len(line) == 0 {
break
}
lines = append(lines, string(line))
}
return lines, err
}
下面的代码示例说明了上述函数的示例用法:
reader := bufio.NewReader(file)
for {
lines, err := myReadLine(file, reader)
if err != nil || len(lines) == 0 {
break
}
fmt.Println(lines)
}
TA贡献1846条经验 获得超7个赞
您的方法有效,但我建议您使用 a bufio.Scanner,默认为逐行扫描。然后,您只需开始逐行读取文件并填充结构。当遇到空行时,将您的结构放入一个切片并从一个新的切片开始。
这是我的一个开源项目中的一个示例,用于演示它:
buffer := [][]string{}
block := []string{}
scanner := bufio.NewScanner(strings.NewReader(data))
for scanner.Scan() {
l := scanner.Text()
if len(strings.TrimSpace(l)) != 0 {
block = append(block, l)
continue
}
// At this point, the script has reached an empty line,
// which means the block is ready to be processed.
// If the block is not empty, append it to the buffer and empty it.
if len(block) != 0 {
buffer = append(buffer, block)
block = []string{}
}
}
if len(block) != 0 {
buffer = append(buffer, block)
}
TA贡献1818条经验 获得超7个赞
破了。首先了解扫描并确保其正常工作:
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
scanner := bufio.NewScanner(strings.NewReader(data))
for scanner.Scan() {
l := scanner.Text()
fmt.Println(l)
}
}
var data = `
Name = "John"
Surname = "Smith"
Val1 = 700
Val2 = 800
Name = "Pete"
Surname = "Jones"
Val1 = 555
Val2 = 666
Val3 = 444
`
这是Go Playground 上的代码。
接下来,将您需要的数据收集到一个切片中。可能有一种方法可以检查文件结尾 EOF,但我找不到它。这就是我想出的并且有效:
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
buffer := [][]string{}
block := []string{}
scanner := bufio.NewScanner(strings.NewReader(data))
for scanner.Scan() {
l := scanner.Text()
if len(l) != 0 {
block = append(block, l)
continue
}
if len(l) == 0 && len(block) != 0 {
buffer = append(buffer, block)
block = []string{}
continue
}
if len(l) == 0 {
block = []string{}
continue
}
}
if len(block) != 0 {
buffer = append(buffer, block)
block = []string{}
}
fmt.Println("PRINTING BUFFER - END OF PROGRAM - ALL DATA PROCESSED:", buffer)
}
var data = `
Name = "John"
Surname = "Smith"
Val1 = 700
Val2 = 800
Name = "Pete"
Surname = "Jones"
Val1 = 555
Val2 = 666
Val3 = 444
`
这是操场上的代码。
- 3 回答
- 0 关注
- 462 浏览
添加回答
举报