Go provides the os
and bufio
packages that make it easy to read files. Here’s an example of how you can read a file line by line in Go:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// Open the file
file, err := os.Open("test.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
// Create a scanner to read the file
scanner := bufio.NewScanner(file)
// Read the file line by line
for scanner.Scan() {
line := scanner.Text()
fmt.Println(line)
}
// Check for errors while reading the file
if err := scanner.Err(); err != nil {
fmt.Println("Error reading file:", err)
}
}
In this example, we first use the os.Open
function to open the file "test.txt"
. The defer file.Close
statement is used to ensure that the file is closed when the program finishes, even if there is an error.
Next, we use the bufio.NewScanner
function to create a scanner that will read the file. The scanner has a Scan
method that returns true
as long as there is another line to read, and the Text
method returns the current line as a string.
We use a for
loop to read the file line by line, and we use the fmt.Println
function to print each line.
Finally, we use the scanner.Err
function to check for any errors that occurred while reading the file.
Leave a Reply