当前位置: > > > > 如何在 Go 中跳过文件的第一行?
如何在 Go 中跳过文件的第一行?
来源:stackoverflow
2024-04-21 11:24:34
0浏览
收藏
大家好,今天本人给大家带来文章《如何在 Go 中跳过文件的第一行?》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
问题内容
如何在 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
今天关于《如何在 Go 中跳过文件的第一行?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注米云公众号!
