W3Basic Logo

Check if a file exists in Go

The os package in Go (Golang) provides a set of functions for interacting with the operating system. It allows you to perform tasks such as creating and deleting files, reading and writing to files, interacting with the file system, and interacting with system environment variables.

In this article, we will look into various ways to check if a file exists in Go using os package.


Using the os.Stat() function:

The os.Stat() function takes a file path as an argument and returns a FileInfo struct that contains information about the file. If the file does not exist, the function will return an error. In this case, we check if the error is os.IsNotExist(), and if so, we know the file does not exist. If the error is not os.IsNotExist(), we print the error message. If there is no error, the file exists.

package main

import (
    "os"
)

func main() {
    // Get the file info
    _, err := os.Stat("file.txt")

    // check if the file exists
    if os.IsNotExist(err) {
        println("File does not exist")
    } else {
        println("File exists")
    }
}

Output

File does not exist

Using the os.Open() function:

The os.Open() function takes a file path as an argument and opens the file for reading. If the file does not exist, the function will return an error. In this case, we check if the error is os.IsNotExist(); if so, we know the file does not exist. If there is no error, the file exists.

package main

import (
    "os"
)

func main() {
    // Open the file
    _, err := os.Open("file.txt")

    // check if the file exists
    if os.IsNotExist(err) {
        println("File does not exist")
    } else {
        println("File exists")
    }
}

Output

File does not exist

Conclusion:

In this article, we have discussed several ways to check if a file exists in Go. The os.Stat() function and os.Open() function check the file's existence by trying to access the file, and if the file does not exist, the operation fails and returns an error.

© 2023 W3Basic. All rights reserved.

Follow Us: