Reading and writing files

Read project files with os.ReadFile or os.Open, parse CSV and JSON, and write temporary files under /tmp.

Runs in Zerethon IDE · Go 1.27 Official Go documentation ↗

A run sees the project's files in its working folder, read-only. A program may write files under /tmp; they are deleted when the run ends.

main.go
package main

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"os"
)

func main() {
	f, err := os.Open("data.csv")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	rows, err := csv.NewReader(f).ReadAll()
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, row := range rows[1:] {
		fmt.Println(row[0], row[1])
	}

	data, _ := json.Marshal(map[string]int{"count": len(rows) - 1})
	if err := os.WriteFile("/tmp/report.json", data, 0o644); err != nil {
		fmt.Println(err)
		return
	}
	back, _ := os.ReadFile("/tmp/report.json")
	fmt.Println(string(back))
}
data.csv
name,score
ada,90
alan,85

Output

ada 90
alan 85
{"count":2}
  • defer f.Close() right after a successful Open closes the file when the function returns.
  • Paths are relative to the project root: os.ReadFile("data/input.txt") reads the file shown in the explorer as data/input.txt.
  • Writing next to your code (os.WriteFile("out.txt", ...)) fails with read-only file system — use /tmp/out.txt.