如何从 Golang 中的文件中读取确切的行

如何在与某些输入相对应的文件中查找和读取行号?我用谷歌搜索了这段代码,但它将文件的全部内容加载到单个数组中,所有行都被索引。没有更简单的方法吗?


func LinesInFile(fileName string) []string {

    f, _ := os.Open(fileName)

    // Create new Scanner.

    scanner := bufio.NewScanner(f)

    result := []string{}

    // Use Scan.

    for scanner.Scan() {

        line := scanner.Text()

        // Append line to result.

        result = append(result, line)

    }

    return result

}


aluckdog
浏览 132回答 1
1回答

Helenr

你应该忽略你不感兴趣的行。func ReadExactLine(fileName string, lineNumber int) string {&nbsp; &nbsp; inputFile, err := os.Open(fileName)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Error occurred! ", err)&nbsp; &nbsp; }&nbsp; &nbsp; br := bufio.NewReader(inputFile)&nbsp; &nbsp; for i := 1; i < lineNumber; i++ {&nbsp; &nbsp; &nbsp; &nbsp; _, _ = br.ReadString('\n')&nbsp; &nbsp; }&nbsp; &nbsp; str, err := br.ReadString('\n')&nbsp; &nbsp; fmt.Println("Line is ", str)&nbsp; &nbsp; return str}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go