gpt4 book ai didi

go - 如何跳过 Go 中文件的第一行?

转载 作者:IT王子 更新时间:2023-10-29 01:46:46 25 4
gpt4 key购买 nike

如何在 Go 中读取文件并跳过第一行/标题?

在 Python 中我知道我可以做到

counter = 0
with open("my_file_path", "r") as fo:
try:
next(fo)
except:
pass
for _ in fo:
counter = counter + 1

这是我的 Go 应用程序

package main    
import (
"bufio"
"flag"
"os"
)

func readFile(fileLocation string) int {
fileOpen, _ := os.Open(fileLocation)
defer fileOpen.Close()
fileScanner := bufio.NewScanner(fileOpen)

counter := 0
for fileScanner.Scan() {
//fmt.Println(fileScanner.Text())
counter = counter + 1
}

return counter
}

func main() {
fileLocation := flag.String("file_location", "default value", "file path to count lines")
flag.Parse()

counted := readFile(*fileLocation)
println(counted)
}

我将读取一个巨大的文件,如果索引为 0,我不想评估每一行。

最佳答案

如何移动到循环前的下一个标记

scanner := bufio.NewScanner(file)
scanner.Scan() // this moves to the next token
for scanner.Scan() {
fmt.Println(scanner.Text())
}

文件

1
2
3

输出

2
3

https://play.golang.org/p/I2w50zFdcg0

关于go - 如何跳过 Go 中文件的第一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54614588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com