}

Golang: How to Check If a File Exists Before Using It

Created:

Introduction

File manipulation is a basic and common problem while programming. In this article we explain how to check if a file exists using GO programming lenguage.

In particular we are going to use standard library in our example code. We will use the os package. This tutorial will help to learn how to check for errors with GO.

Solution of how to verify if a file exists with GO

Our example code will use command line arguments as an input for filename. To read command line arguments we also use the os package.

The Stat function returns the FileInfo structure describing file. In our code we don't care about the result returned, we focus more on the err Using IsNotExist we verify if the error returned refer to file does not exist.

package main

import (
    "fmt"
    "os"
)

func main() {
    filename := os.Args[0]
    _, err := os.Stat(filename); 
    if os.IsNotExist(err) {
        fmt.Println("File does not exist")
    } else {
        fmt.Println("File exists")
    }
}

We import fmt to print the error on the screen.