Cookies management by TermsFeed Cookie Consent

๐Ÿงน Delete or remove a file in Go

shorts introduction file

To delete/remove a file in Go, use the built-in os.Remove() function:

package main

import (
    "log"
    "os"
)

func main() {
    if err := os.Remove("testfile.txt"); err != nil {
        log.Fatal(err)
    }
}

If the file exists, the function removes the file without any error. If there is some problem, it returns an error of type *os.PathError. For example, if the file does not exist, the error is:

2022/04/05 06:16:05 remove testfile.txt: no such file or directory
exit status 1

Thank you for being on our site ๐Ÿ˜Š. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

๐Ÿค Create a new file in Go

shorts introduction file

๐Ÿพ How to compare strings in Go

shorts introduction strings

๐Ÿ›‘ Exit an app in Go

shorts introduction os