To read and process a file line by line in Go using the bufio.Scanner
, you can follow these steps:
import (
"bufio"
"fmt"
"os"
)
file, err := os.Open("file.txt")
if err != nil {
panic(err)
}
defer file.Close()
bufio.Scanner
by passing the opened file as input:scanner := bufio.NewScanner(file)
Scan
method of the scanner:for scanner.Scan() {
line := scanner.Text()
// Process the line as needed
fmt.Println(line)
}
if err := scanner.Err(); err != nil {
panic(err)
}
Here's a complete example:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
panic(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
// Process the line as needed
fmt.Println(line)
}
if err := scanner.Err(); err != nil {
panic(err)
}
}
Make sure to replace "file.txt"
with the actual path of the file you want to read and process line by line.