How to delete a file using the os package in Golang?

To delete a file using the os package in Golang, you can use the Remove or RemoveAll function provided by the package. Here's an example demonstrating both approaches:

package main import ( "fmt" "os" ) func main() { // Define the path and name of the file to delete filePath := "path/to/file.txt" // Remove the file err := os.Remove(filePath) if err != nil { fmt.Println("Error deleting file:", err) return } fmt.Println("File deleted successfully.") // Alternatively, you can use RemoveAll if you need to remove directories as well // RemoveAll(path) removes path and any children it contains // It is similar to running "rm -rf" on the command line dirPath := "path/to/directory" err = os.RemoveAll(dirPath) if err != nil { fmt.Println("Error deleting directory:", err) return } fmt.Println("Directory deleted successfully.") }

Ensure that you have the necessary file/directory permissions to delete the file/directory.