C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
In Go we can use the bufio package to read in all the lines in this file inside a loop. With Scan and Text we get a string for each line.
With bufio, we have many helpful methods for handling text files. Newlines are handled automatically. The classes are easy to use with some practice.
First example. This program opens a file on the disk. Please change the path argument to os.Open to a file that exists on your computer. Errors are not handled here.
Open: This returns a *File descriptor. We can pass the result of Open() to the bufio.NewScanner method.
NewScanner: This creates a new *Scanner. The File we pass to this method is accessed through its Reader interface.
Scan: This advances to the next part of the file and returns true if there is more data. And text() creates a string from the current line.
Based on: Golang 1.4 Golang program that uses bufio, reads text file package main import ( "bufio" "fmt" "os" ) func main() { // Open the file. f, _ := os.Open("C:\\programs\\file.txt") // Create a new Scanner for the file. scanner := bufio.NewScanner(f) // Loop over all lines in the file and print them. for scanner.Scan() { line := scanner.Text() fmt.Println(line) } } Output Carrot Bird Fish Turnip Contents of file.txt Carrot Bird Fish Turnip
ScanWords. A file sometimes contains words. We can get each word separately as a string with the Scan() and Text() methods. First we must call Split.
Tip: The Split method here just sets the splitting method for the scanner. It influences the behavior of Scan().
Golang program that uses bufio.ScanWords, gets words package main import ( "bufio" "fmt" "os" ) func main() { f, _ := os.Open("C:\\programs\\file.txt") scanner := bufio.NewScanner(f) // Set the Split method to ScanWords. scanner.Split(bufio.ScanWords) // Scan all words from the file. for scanner.Scan() { line := scanner.Text() fmt.Println(line) } } Output a commodius vicus of recirculation Contents of file.txt a commodius vicus of recirculation
In file handling, errors are common and often unavoidable. We use the error return value from os.Open, and the recover() method, to handle these events.