📜  如何在 Golang 中删除或移除文件?

📅  最后修改于: 2021-10-24 13:24:37             🧑  作者: Mango

在 Go 语言中,您可以借助Remove() 方法删除现有文件。此方法从导演中删除指定的文件,或者也删除空目录。如果给定的路径不正确,则会抛出 *PathError 类型的错误。它定义在 os 包下,因此您必须在程序中导入 os 包才能访问 Remove()函数。

句法:

func Remove(file_name string) error

示例 1:

// Golang program to illustrate how to 
// remove files from the default directory
package main
   
import (
    "log"
    "os"
)
   
func main() {
  
    // Removing file from the directory
    // Using Remove() function
     e := os.Remove("GeeksforGeeks.txt")
    if e != nil {
        log.Fatal(e)
    }
}

输出:

前:

在 Golang 中删除文件之前

后:

在 Golang 中删除文件后

示例 2:

// Golang program to illustrate how to remove
// files from the specified directory
package main
    
import (
    "log"
    "os"
)
    
func main() {
   
    // Removing file
    // Using Remove() function
    e := os.Remove("/Users/anki/Documents/new_folder/GeeksforGeeks.txt")
    if e != nil {
        log.Fatal(e)
  
   } 
}

输出:

前:

在 Golang 中删除文件之前

后:

在 Golang 中删除文件后