Read and write file in Golang / File handling in Golang

In this tutorial, you will learn the most basic techniques using os. File. There are several ways that can be used for file operations in Go. In this tutorial you will learn how to create, edit, read and delete files using Golang

Creating New Files in Golang

In Go it's very easy to create files, just call the os.Create() function and then enter the path of the file you want to create as a parameter. If it turns out that the file to be created already exists, it will be overwritten. Can use os.IsNotExist() to detect whether the file has been created or not.

The following is an example of creating a file.


package main

import (
    "fmt"
    "os"
)

var path = "C:/Users/Desktop/Golang/Tutorials/test.txt"

func isError(err error) bool {
    if err != nil {
        fmt.Println(err.Error())
    }

    return (err != nil)
}

func createFile() {
    // detect if the file already exists
    var _, err = os.Stat(path)

    // create a new file if it doesn't already exist
    if os.IsNotExist(err) {
        var file, err = os.Create(path)
        if isError(err) {
            return
        }
        defer file.Close()
    }

    fmt.Println("==> file created successfully", path)
}

func main() {
    createFile()
}

Output:


PS C:\Users\Desktop\Golang> go run file.go
==> file created successfully C:/Users/Desktop/Golang/Tutorials/test.txt
PS C:\Users\Desktop\Golang>

The os.Stat() the function returns 2 data, namely information about the path being searched for, and an error (if any). Enter the function's return error as a parameter of the os.IsNotExist() function, to detect whether the file to be created already exists. If it doesn't exist, the function will return true.

The os.Create() the function is used to create a file at a specified path. This function returns the *os. File object of the corresponding file. The newly created file status is automatically open, therefore it needs to be closed using the file.Close() method after the file is no longer used.

Leaving a file open when it is no longer in use is not a good thing, because it affects memory and access to the file itself, the file will be locked so that it cannot be used by other processes as long as the file status is still open or not closed.

Editing File Contents in Golang

To edit a file, what you need to do first is to open a file with a write access level. After getting the file object, use the WriteString() method to fill in the data. Finally, call the Sync() method to save the changes.

Program to edit file contents


package main

import (
    "fmt"
    "os"
)

var path = "C:/Users/Desktop/Golang/Tutorials/test.txt"

func writeFile() {
    // open file with access level READ & WRITE
    var file, err = os.OpenFile(path, os.O_RDWR, 0644)
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // write data to file
    _, err = file.WriteString("hello\n")

    if err != nil {
        panic(err)
    }
    _, err = file.WriteString(" golang\n")
    if err != nil {
        panic(err)
    }

    // save changes
    err = file.Sync()
    if err != nil {
        panic(err)
    }

    fmt.Println("==> file successful")
}

func main() {
    writeFile()
}

Output:


PS C:\Users\Desktop\Golang> go run file.go
==> file successful
GO : Files

In the above program, the file is opened with reading and writing access levels with the permission code 0664. After that, some strings are entered into the file using WriteString(). In the end, all changes to the file will be saved by calling Sync().

Reading File Contents in Golang

The file you want to read must be opened first using the os.OpenFile() function with the minimum access level being read. After that, use the Read() method where the parameter is a variable, which is where the result of the reading process will be saved to that variable.

Program to read file contents


package main

import (
    "fmt"
    "io"
    "os"
)

var path = "C:/Users/Desktop/Golang/Tutorials/test.txt"

func readFile() {
    // open file
    var file, err = os.OpenFile(path, os.O_RDONLY, 0644)
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // read file
    var text = make([]byte, 1024)
    for {
        n, err := file.Read(text)
        if err != io.EOF {
            if err != nil {
                panic(err)
            }
        }
        if n == 0 {
            break
        }
    }
    if err != nil {
        panic(err)
    }

    fmt.Println("==> file read successfully")
    fmt.Println(string(text))
}

func main() {
    readFile()
}

Output:


PS C:\Users\Desktop\Golang> go run readfile.go
==> file read successfully
hello
 golang

The above code os.OpenFile() is used to open the file. The function has several parameters.

The first parameter is the path of the file to be opened.
The second parameter is the access level. os.O_RDONLY means read-only.
The third parameter is the file permissions.
The text variable is prepared with the type of slice []byte with an element allocation of 1024. This variable is in charge of accommodating the data resulting from the file.Read() statement. The process of reading the file will be carried out continuously, sequentially from the first line to the end.

Errors that appear when executing the file.Read() will be filtered, when the error is other than io.EOF then the file reading process will continue. The io.EOF error itself indicates that the file being read is the last line of content or the end of the file.

Deleting Files in Golang

How to delete a file is very easy, just call the os.Remove() function, enter the path of the file you want to delete as a parameter.


package main

import (
 "fmt"
 "os"
)

var path = "C:/Users/Desktop/Golang/Tutorials/test.txt"

func deleteFile() {
 var err = os.Remove(path)
 if err != nil {
  panic(err)
 }

 fmt.Println("==> file deleted successfully")
}

func main() {
 deleteFile()
}


Output:


Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.

PS C:\Users\Desktop\Golang> go run delfile.go
==> file deleted successfully