TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Golang Read Text Files: bufio Examples

This Go tutorial uses bufio, NewScanner, Scan and Text to read the lines of a file into strings. It uses for-loops.

Bufio, read text. A file contains many lines.

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf