go · level 2 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A keeps your data after the boxes are gone.
Everything in your boxes vanishes when the program ends. A file keeps data saved, like a page in a notebook. On Gwecode every run starts in its own empty folder, so the files you make last for that run only.
saves text into a file. Files hold bytes, so []byte(text) turns the string into a first. 0644 says who may read and change the file: use it every time.
reads the whole file back as a byte slice, and string(data) turns it into text. Both commands return an error value, because files go missing. errors.Is(err, os.ErrNotExist) spots a missing one.
package main
import "fmt"
import "os"
func main() {
err := os.WriteFile("notes.txt", []byte("Feed the cat\nBuy milk\n"), 0644)
if err != nil {
fmt.Println("Could not save:", err)
return
}
data, err := os.ReadFile("notes.txt")
if err != nil {
fmt.Println("Could not read:", err)
return
}
fmt.Print(string(data))
fmt.Println(len(data), "bytes")
} Writing to a file that already exists replaces everything that was in it.
guess first
Nothing has been saved yet. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "errors"
import "fmt"
import "os"
func main() {
_, err := os.ReadFile("diary.txt")
if errors.Is(err, os.ErrNotExist) {
fmt.Println("No diary yet, starting a new one")
} else if err != nil {
fmt.Println("Something else went wrong")
} else {
fmt.Println("Diary loaded")
}
}
your turn
Your turn. Save a wish in a file.
Type a wish to save in the file. Then read the same file back by typing its name, wish.txt, in the second blank.
output
press run to see what happens
fix it
Tonight's menu comes out as numbers. Fix it!
output
press run to see what happens
- The menu shows a row of numbers. What kind of value does
os.ReadFilehand back? - It hands back a byte slice, with each letter kept as a number. Turn it back into text.
- Change data to string(data) on line 11, then run.
nailed it
your programs can remember things now. :D
os.WriteFilesaves a byte slice into a file.os.ReadFilereads it back, andstring(data)turns it into text.- Check the error, because files can go missing.
new words in your collection
- file
- byte slice
- WriteFile
- ReadFile
This lesson isn’t saved. A free account remembers every lesson you finish.