Golang program to delete a file


Golang has os package that is used for deleting a file. In this os package the filename that we wish to delete is initially specified. The file is then deleted using the os.Remove method from the os package.In this article we are using two example to demonstrate the process of deleting a file.

Syntax

os.Remove()

The os.Remove function in Go is used to delete a file or directory identified by a file path. The file or directory path that you want to remove is the only argument for this function.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package), os package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Create a filename variable and assign it to the file which has to be deleted.

  • Step 3 − Then, use os.Remove function with filename as the input and if error appears while removing the file print the error.

  • Step 4 − If no error appears, this means that file is deleted successfully and a success message is printed.

  • Step 5 − The print statement is executed fmt.Println() function where ln means new line.

Example 1

In this example, we will use os package functions to execute the program.

package main
import (
   "os"
   "fmt"
)

func main() {
   fileName := "file.txt"    //create a file 
   err := os.Remove(fileName) //remove the file
   if err != nil {
      fmt.Println("Error: ", err) //print the error if file is not removed
   } else {
      fmt.Println("Successfully deleted file: ", fileName) //print success if file is removed
   }
}

Output

If file is removed successfully
Successfully deleted file: file.txt

If file is not removed successfully
file not found 

Example 2

In this example, we will use log package functions to delete a file.

package main
import (
   "log"
   "os"
)

func main() {
   filePath := "myfile.txt"  //create a file which will be deleted 
   errs := os.Remove(filePath)//remove the file using built-in functions
   if errs != nil {
      log.Fatalf("Error removing file: %v", errs) //print error if file is not removed
   }
   log.Printf("File %s removed successfully", filePath) //print success if file is removed
}

Output

If file is removed successfully
2023/02/09 23:59:59 File test.txt removed successfully

If file is not removed successfully
2023/02/09 23:59:59 Error removing file: open file.txt: The system cannot find the file specified.

Conclusion

We executed the program of deleting a file using two examples. In the first example, we imported os package and used the following functions to delete the file whereas in the second example we used log package along with os package to delete the files.

Updated on: 22-Feb-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements