How to Read File Line by Line in Go: Simple Guide
In Go, you can read a file line by line using
bufio.Scanner. Open the file with os.Open, create a scanner with bufio.NewScanner, then loop with scanner.Scan() to read each line.Syntax
To read a file line by line in Go, you typically use these steps:
os.Opento open the file.bufio.NewScannerto create a scanner for the file.- Use
scanner.Scan()in a loop to read each line. scanner.Text()gives the current line as a string.- Always check for errors with
scanner.Err()after the loop.
go
file, err := os.Open("filename.txt") if err != nil { // handle error } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() // process line } if err := scanner.Err(); err != nil { // handle error }
Example
This example shows how to open a file named example.txt and print each line to the console.
go
package main import ( "bufio" "fmt" "os" ) func main() { file, err := os.Open("example.txt") if err != nil { fmt.Println("Error opening file:", err) return } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() fmt.Println(line) } if err := scanner.Err(); err != nil { fmt.Println("Error reading file:", err) } }
Output
Hello, world!
This is line 2.
Last line here.
Common Pitfalls
Common mistakes when reading files line by line in Go include:
- Not closing the file with
defer file.Close(), which can cause resource leaks. - Ignoring errors from
scanner.Err()after the loop. - Using
ioutil.ReadAllor reading the whole file at once when only line-by-line reading is needed. - Assuming lines end with
\nonly;bufio.Scannerhandles line endings correctly.
go
/* Wrong way: Not closing file and ignoring errors */ file, _ := os.Open("file.txt") scanner := bufio.NewScanner(file) for scanner.Scan() { fmt.Println(scanner.Text()) } // Missing file.Close() and error check /* Right way: */ file, err := os.Open("file.txt") if err != nil { // handle error } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { // handle error }
Quick Reference
Remember these key points when reading files line by line in Go:
- Use
os.Opento open files. - Create a scanner with
bufio.NewScanner. - Loop with
scanner.Scan()to read lines. - Get each line with
scanner.Text(). - Always close the file and check for errors.
Key Takeaways
Use bufio.Scanner with os.Open to read files line by line efficiently.
Always close the file with defer to avoid resource leaks.
Check for errors after scanning with scanner.Err().
Avoid reading the entire file if you only need line-by-line processing.
bufio.Scanner handles different line endings automatically.