Working with files

The os package (https://golang.org/pkg/os/) exposes the os.File type which represents a file handle on the system. The os.File type implements several IO primitives, including the io.Reader and io.Writer interfaces, which allows file content to be processed using the standard streaming IO API.

Creating and opening files

The os.Create function creates a new file with the specified path. If the file already exists, os.Create will overwrite it. The os.Open function, on the other hand, opens an existing file for reading.

The following source snippet opens an existing file and creates a copy of its content using the io.Copy function. One common, and recommended practice to notice is the deferred call to the method Close on the file. ...

Get Go: Design Patterns for Real-World Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.