Как я могу пропустить первую строку файла в Go? - PullRequest
0 голосов
/ 10 февраля 2019

Как я могу прочитать файл в 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.

Ответы [ 3 ]

0 голосов
/ 10 февраля 2019

Например,

package main

import (
    "bufio"
    "fmt"
    "os"
)

func readFile(filename string) (int, error) {
    f, err := os.Open(filename)
    if err != nil {
        return 0, err
    }
    defer f.Close()

    count := 0
    s := bufio.NewScanner(f)
    if s.Scan() {
        for s.Scan() {
            count++
        }
    }
    if err := s.Err(); err != nil {
        return 0, err
    }
    return count, nil
}

func main() {
    filename := `test.file`

    count, err := readFile(filename)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        return
    }
    fmt.Println(count)
}

Вывод:

$ cat test.file
1234567890
abc
$ go run count.go
1
$ 
0 голосов
/ 21 июня 2019

Как насчет перехода к следующему токену перед циклом

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

file

1
2
3

output

2
3

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

0 голосов
/ 10 февраля 2019

Вы можете попробовать что-то вроде этого

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
        }

Редактировать:

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
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...