How to work with files in Golang

how to work with files in golang

Create, read, write and append to file in Golang

Setup workspace

In your workspace of choice in your computer, create a working directory and add a go file to add our code. Follow the below steps

$ mkdir src
$ cd src
$ touch main.go
$ go mod init example/src

Please note that the src directory can be named to anything you want. We also initialize go modules, to help us keep track of dependencies on our code.

Create a file in Golang

Creating a file is a basic feature for any programming language. In Go, creating file operations is very easy to implement. We will use  the os package that is in the standard library to create a file. In Go the os package provides two methods that can be used to  create a file name;

  1. os.Create()
  2. os.OpenFile()

Using os.Create()

The os.Create() method  is used to create a file in your program. It takes the name of the file to create as a parameter and returns the created file as a pointer and an error if any exists.  If the file already exists it will be truncated. If the file does not exist, it will be created with mode 0666 (before umask). If file creation is successful, methods on the returned file can be used for I/O.  The file will be associated with a descriptor of mode 0_RDWR. If an error is returned it will be of type *PathError.

Example

package main
 
import (
   "log"
   "os"
)
 
func main() {
   filename := "log.txt"
 
   file, err := os.Create(filename)
 
   if err != nil {
       log.Fatal(err)
   }
   defer file.Close()
}

Explanation

In the above example, we are using the os.Create() method to create a file  called log.txtos.Create() takes as an argument the name of the file that should be created. os.Create() returns an instance of the created file and error object. To run the above code, in your terminal in the same path as the main.go file, issue this command $ go run main.go. A

file will be created in your root folder if the code runs successfully.