We can use Golang “bufio” package along with the “os” package to read the contents of a file line by line.
The process to read a text file line by line include the following steps:
- Use os.open() function to open the file.
- Use bufio.NewScanner() function to create the file scanner.
- Use bufio.ScanLines() function with the scanner to split the file into lines.
- Then use the scanner Scan() function in a for loop to get each line and process it.
Here is the complete code to read a text file line by line and print in Golang.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
readFile, err := os.Open("data.txt")
if err != nil {
fmt.Println(err)
}
fileScanner := bufio.NewScanner(readFile)
fileScanner.Split(bufio.ScanLines)
for fileScanner.Scan() {
fmt.Println(fileScanner.Text())
}
readFile.Close()
}
Note: The data.txt file should be in the same directory as the above program, else you will get an error printed as “open data.txt: no such file or directory”.
Reading File line by line to String Array
The above program has two issues:
- The text file path is hardcoded, let’s read it from the command line argument.
- We are processing the file lines, which is keeping our resources open for longer time. We can read the file data into a string array and then process it accordingly. This is not recommended for a very large file though.
Here is the updated code to read file path from command line and save its lines into a string array.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
filePath := os.Args[1]
readFile, err := os.Open(filePath)
if err != nil {
fmt.Println(err)
}
fileScanner := bufio.NewScanner(readFile)
fileScanner.Split(bufio.ScanLines)
var fileLines []string
for fileScanner.Scan() {
fileLines = append(fileLines, fileScanner.Text())
}
readFile.Close()
for _, line := range fileLines {
fmt.Println(line)
}
fmt.Println(fileLines)
}
I have saved the above file as “read_file.go”. Let’s see how to run it from the command line.
% go run read_file.go data.txt
Hello World
I love Go Programming
Bye Bye
[Hello World I love Go Programming Bye Bye]
%
Conclusion
It’s very easy to read a file in Go programming. We can read the file contents line by line and process them or we can store into a string array and process them later on. We should always close the file resources as soon as our work is done.
Further Readings: Golang os package, Golang command-line arguments, Golang Download File.