go · level 2 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A reads a file, or typed input, line by line.
os.ReadFile grabs a whole file at once. For a long file, it is often better to work through it a line at a time. opens the file, and defer f.Close() makes sure it gets closed again.
scanner := bufio.NewScanner(f) makes a Scanner from the bufio toolbox. Each scanner.Scan() moves to the next line and gives true, or false when none are left. So for scanner.Scan() { loops once per line, and scanner.Text() is that line.
is the text typed into your program, and a Scanner reads it the same way: bufio.NewScanner(os.Stdin). Unlike fmt.Scan, it keeps the spaces, so it reads a whole sentence at once.
package main
import "bufio"
import "fmt"
import "os"
func main() {
os.WriteFile("pets.txt", []byte("Rex the dog\nTibbles the cat\nGoldie the fish\n"), 0644)
f, err := os.Open("pets.txt")
if err != nil {
fmt.Println("No pets file")
return
}
defer f.Close()
scanner := bufio.NewScanner(f)
count := 0
for scanner.Scan() {
count++
fmt.Printf("%d: %s\n", count, scanner.Text())
}
} for scanner.Scan() is the while loop you already know: a for with only a condition.
guess first
Two lines are typed in. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "bufio"
import "fmt"
import "os"
import "strings"
func main() {
scanner := bufio.NewScanner(os.Stdin)
lines := 0
for scanner.Scan() {
lines++
fmt.Println(strings.ToUpper(scanner.Text()))
}
fmt.Println(lines, "lines")
}
your turn
Your turn. Tick through the shopping list.
Add one item of your own to the end of the list file. Then open that file, make sure it gets closed, and fill in the Scanner method that moves to each next line.
output
press run to see what happens
fix it
The welcome forgets your name. Fix it!
output
press run to see what happens
- The name comes out empty. A Scanner has nothing to give until it has read a line.
scanner.Scan()reads the next line, and only after that doesscanner.Text()hold it.- Swap lines 8 and 9, so Scan comes before Text, then run.
nailed it
you can read anything line by line. :D
os.Openopens a file, anddefer f.Close()closes it.for scanner.Scan()loops once per line, andscanner.Text()is the line.- A Scanner on
os.Stdinreads typed lines, spaces and all.
new words in your collection
- os.Open
- Scanner
- os.Stdin
This lesson isn’t saved. A free account remembers every lesson you finish.