Go · Chapter 13 of 26
Files and io
By the end of this chapter you can read and write whole files, open a file and close it with defer, read input line by line with bufio.Scanner, read CSV with encoding/csv, tell "the file is not there" from every other error, and write functions that take an io.Reader or an io.Writer, so the same code works on a file, a string, a network connection or a test's buffer. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Real programs
- 4 tasks
- Go
- In the all labs plan
The first 2 chapters of Go are free. This one comes with the all labs plan.
Why you need this
BijliGo's programs live among files. Tenzin exports meter readings as CSV for the evening review. Every charger keeps a log, one event a line, and when C1057 at Bellandur Hospital faulted at 7:12 pm on Wednesday, the answer was in that log. Nandini wants the daily report on her screen, in a file and in an email. And Pooja can change the tariffs by putting a JSON file on the server, which means the file may be there, may be broken, or may not be there at all.
You can already turn JSON into structs (chapter 12), but only from a []byte you already have. Reading a 2 GB log into memory just to count its fault lines is wasteful, and a function that opens a file by name can only be tested with a real file on disk. Go's answer is two tiny interfaces, io.Reader and io.Writer, that almost everything in the standard library speaks.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
energy.go: the energy in a CSV of meter readings
Write TotalEnergy(r io.Reader) (int, error). It reads CSV from r: a header row session,charger,at,meter_wh,power_w, then one meter reading a row, such as S900710,C1002,2026-10-14T06:42:00+05:30,590,35405. meter_wh is the energy so far in that session and only goes up, so a session's energy is its largest meter_wh. TotalEnergy returns the energy of all the sessions added up, in watt-hours.
For ST001's 1263 readings (24 sessions) it returns 345154. The Check also tries two sessions whose readings end at 1400 Wh and 450 Wh, mixed together (1850), and only the header row (0, no error).
It returns an error when a meter_wh is not a whole number (the Check uses lots) and when a row has the wrong number of fields.
- Task 2
report.go: the daily report, written to any io.Writer
Write WriteReport(w io.Writer, sessions []bijli.Session) error. It writes the day's report to w; for Wednesday's 3600 sessions, exactly these lines:
BijliGo daily report
Sessions: 3600
Completed: 3049
Stopped early: 442
Failed: 109
Energy: 44632.024 kWh
Revenue: 831588.05 rupees
Completed, Stopped early and Failed count the statuses completed, stopped_early and failed. Energy adds EnergyWh and shows it in kWh with exactly three digits after the point; Revenue adds CostPaise and shows rupees with exactly two. The Check also tries the first 250 sessions (Sessions: 250, Completed: 208, Stopped early: 34, Failed: 8, Energy: 2915.870 kWh, Revenue: 51613.01 rupees) and no sessions at all (every number 0, Energy: 0.000 kWh, Revenue: 0.00 rupees).
When writing to w fails, WriteReport returns that error: the Check gives it a writer whose every write fails.
- Task 3
tariffs.go: a tariffs file that may not be there
Write LoadTariffs(path string) ([]bijli.Tariff, error) and SaveTariffs(path string, tariffs []bijli.Tariff) error.
LoadTariffs reads the file at path, a JSON list of tariffs in bijli.Tariff's shape, and returns them. When the file does not exist, it returns bijli.Tariffs() (BijliGo's four, AC7 first) and a nil error. When the JSON is broken, or reading fails for any other reason (the Check passes a folder), it returns the error.
SaveTariffs writes the tariffs to path as JSON indented by two spaces (so the file has the line "paise_per_kwh": 2600 for a DC60 tariff of 2600 paise). The Check saves DC60 at 2600 and LEV3 at 950, and LoadTariffs must read those two back.
- Task 4 · interview question
Interview: faults.go, a file name or an io.Reader?
Each charger keeps a log, one event a line, such as 2026-10-14T19:12:03+05:30 C1057 FAULT overcurrent. A line is a fault when its third word is FAULT (the Check's log has a line that says FAULT later on, which is not one).
Write CountFaults(r io.Reader) (int, error), which reads the log from r line by line and returns how many fault lines it has: 3 for the Check's log of 5 lines, 6 for a bytes.Buffer with that log twice, 0 for an empty log.
Write CountFaultsInFile(path string) (int, error), which opens the file, counts with CountFaults, and closes the file. The Check calls it 50 times and fails if the files stay open. For a file that does not exist it returns os.Open's error (errors.Is(err, fs.ErrNotExist) is true).
Joseph will ask: should a function take a file name, or an io.Reader? Which one can you test without a file?
What you will learn
- os.ReadFile and os.WriteFile: a whole file in or out, in one call.
- errors.Is(err, fs.ErrNotExist): the file is not there, and nothing else.
- os.Open and defer: open a file, and close it on every way out.
- bufio.Scanner: read input one line at a time.
- io.Reader and io.Writer: anything you can read from or write to.
- fmt.Fprintf, strings.NewReader, bytes.Buffer: writing to a writer, and readers and writers for tests.
- encoding/csv: rows and fields, quotes and commas handled.
More in Real programs
Build "Files and io" yourself
BijliGo, a Bengaluru EV charging network, drops chargers at the evening peak. You rewrite its backend in Go. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Go are free. This one comes with the all labs plan.