liveBook · Manning

Os.Open

As explained in Go in Practice, Second Edition

os.Open is a Go standard-library function that opens a file and returns a file handle for subsequent operations.

os.Open opens a file and returns a handle for controlled, sequential processing. Check the error, defer file.Close(), and use the handle for metadata inspection or incremental reads instead of loading the entire file into memory. section 7.1.1

Listing 7.4 Using bufio to read line by line
package main

import (
    "bufio"
    "encoding/json"
    "log"
    "os"
)

func main() {
    file, err := os.Open("structured.log")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    scan := bufio.NewScanner(file)        #1
    scan.Split(bufio.ScanLines)                 #2
    lineJSON := make(map[string]interface{})
    for scan.Scan() {                          #3
        if err := json.Unmarshal([]byte(scan.Text()), &lineJSON); err != n
        il {
            log.Println(err)
        } else {
            log.Println(lineJSON["level"])
        }
    }
}

Wrap the opened handle in bufio.Scanner to process newline-separated JSON records one line at a time. section 7.1.1

How Go in Practice, Second Edition covers it

How deep it goes
Explains opening, error handling, closure, metadata inspection, and incremental reads, but stops short of broader file-management operations.
Examples
Uses structured.log, file.Stat(), newline-separated JSON records, and bufio.Scanner.
What you can do after
Operate/configure file handles to inspect metadata and process large, structured files incrementally.
How it connects
Connects os.ReadFile with file descriptors, file metadata, bufio.Scanner, and JSON parsing.

Also explained in

Compare how 2 books explain os.Open →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.