如何在 Go 中读取文件并跳过第一行/标题?
在Python中我知道我可以做
counter = 0
with open("my_file_path", "r") as fo:
try:
next(fo)
except:
pass
for _ in fo:
counter = counter + 1
Run Code Online (Sandbox Code Playgroud)
这是我的 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)
}
Run Code Online (Sandbox Code Playgroud)
我将读取一个巨大的文件,并且不想在索引为 0 时评估每一行。
如何在循环之前移动到下一个标记
scanner := bufio.NewScanner(file)
scanner.Scan() // this moves to the next token
for scanner.Scan() {
fmt.Println(scanner.Text())
}
Run Code Online (Sandbox Code Playgroud)
文件
1
2
3
Run Code Online (Sandbox Code Playgroud)
输出
2
3
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/I2w50zFdcg0
Ank*_*nde -1
你可以尝试这样的事情
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
}
Run Code Online (Sandbox Code Playgroud)
编辑:
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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7003 次 |
最近记录: |