dongmo8943 2019-02-10 08:13
浏览 503

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

How can I read a file in Go and skip the first line / headers?

In Python I know I could do

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

This is my Go application

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)
}

I will be reading a huge file and don't want to be evaluating each line if the index is 0.

  • 写回答

3条回答 默认 最新

  • doubenggua9430 2019-02-10 08:49
    关注

    you can try something like this

    func readFile(fileLocation string) int {
                fileOpen, _ := os.Open(fileLocation)
                defer fileOpen.Close()
                fileScanner := bufio.NewScanner(fileOpen)
                counter := 0
                for fileScanner.Scan() {
                    // read first line and ignore
                    fileScanner.Text()
                    break
                }
    
               for fileScanner.Scan() {
                    // read remaining lines and process
                    txt := fileScanner.Text()
                    counter = counter + 1
                   // do something with text
                }
    
    
                return counter
            }
    

    Edit:

    func readFile(fileLocation string) int {
                fileOpen, _ := os.Open(fileLocation)
                defer fileOpen.Close()
                fileScanner := bufio.NewScanner(fileOpen)
                counter := 0
                if fileScanner.Scan() {
                    // read first line and ignore
                    fileScanner.Text()
                }
    
               for fileScanner.Scan() {
                    // read remaining lines and process
                    txt := fileScanner.Text()
                   // do something with text
                   counter = counter + 1
                }
    
    
                return counter
            }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)