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

标签 go

如何在 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/

相关文章:

go - if/else 范围内的多个临时变量

c++ - C++ 中的上下文选择功能

php - 将嵌套循环内生成的数据存储在映射或 slice 中

cryptography - 如何将 ECDSA 曲线规范从 SEC2 形式转换为 Go 需要的形式?

json - 从 Java 到 Golang : Unmarshaling Polymorphic JSON

inheritance - 以另一个接口(interface)的形式实现一个接口(interface)

go - BigQuery - 我可以对查询运行查询吗?

go - Go 有分部类吗?

Go:命令行标志