Home >Backend Development >Golang >How to Read a Text File in Golang?

How to Read a Text File in Golang?

Susan Sarandon
Susan SarandonOriginal
2024-11-18 22:37:02599browse

How to Read a Text File in Golang?

How to Read a Text File

In Golang, reading a text file involves opening it using os.Open() and then using the returned *os.File object to perform read operations. However, simply opening the file will not retrieve its contents.

Reading File Content

To obtain file contents, you can use io.ReadAll or manually read in chunks.

Using io.ReadAll:

b, err := io.ReadAll(file)
fmt.Print(b)

This method reads the entire file into memory, which is suitable for smaller files.

Manual Chunked Reading:

buf := make([]byte, 32*1024)
for {
    n, err := file.Read(buf)
    if n > 0 {
        fmt.Print(buf[:n])
    }
    if err == io.EOF {
        break
    }
    if err != nil {
        log.Printf("read %d bytes: %v", n, err)
        break
    }
}

In this approach, you define a buffer and read file contents in chunks, which can be more efficient for large files.

Using the bufio Package

The bufio package provides a convenient way to read text files. It offers the bufio.Scanner type that simplifies tokenizing file contents:

scanner := bufio.NewScanner(file)
for scanner.Scan() {             
    fmt.Println(scanner.Text())
}

The Scan() method advances the scanner's token based on a separator (by default, newlines).

The above is the detailed content of How to Read a Text File in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn