如何在 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 - 如何跳过 Go 中文件的第一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54614588/