Go語言程式刪除檔案


Go 語言擁有 os 包,用於刪除檔案。在這個 os 包中,首先指定要刪除的檔名。然後,使用 os 包中的 os.Remove 方法刪除檔案。本文使用兩個示例演示刪除檔案的過程。

語法

os.Remove()

Go 語言中的 os.Remove 函式用於刪除由檔案路徑標識的檔案或目錄。要刪除的檔案或目錄路徑是此函式的唯一引數。

演算法

  • 步驟 1 − 建立一個 package main 並宣告 fmt(格式化包)、os 包在程式中,其中 main 生成可執行程式碼,fmt 幫助格式化輸入和輸出。

  • 步驟 2 − 建立一個檔名變數並將其分配給要刪除的檔案。

  • 步驟 3 − 然後,使用 os.Remove 函式,將檔名作為輸入,如果在刪除檔案時出現錯誤,則列印錯誤。

  • 步驟 4 − 如果沒有出現錯誤,則表示檔案已成功刪除,並列印成功訊息。

  • 步驟 5 − 執行列印語句 fmt.Println() 函式,其中 ln 表示換行。

示例 1

在本例中,我們將使用 os 包函式來執行程式。

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
   }
}

輸出

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

If file is not removed successfully
file not found 

示例 2

在本例中,我們將使用 log 包函式來刪除檔案。

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
}

輸出

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.

結論

我們使用兩個示例執行了刪除檔案的程式。在第一個示例中,我們匯入了 os 包並使用以下函式刪除檔案,而在第二個示例中,我們使用 log 包以及 os 包來刪除檔案。

更新於: 2023年2月22日

4K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.