如何在Go語言中檢查檔案是否存在?


為了檢查給定目錄中是否存在特定檔案,在Golang中,我們可以使用Go標準庫提供的**os**包中的**Stat()**和**isNotExists()**函式。

**Stat()**函式用於返回描述檔案的fileInfo結構。讓我們首先只使用**Stat()**函式,看看它是否足以檢測Go中檔案的存在。

示例1

考慮以下程式碼。

package main
import(
   "fmt"
   "os"
)
func main() {
   if _, err := os.Stat("sample.txt"); err == nil {
      fmt.Printf("File exists\n");
   } else {
      fmt.Printf("File does not exist\n");
   }
}

在上面的程式碼中,我們嘗試使用**os.Stat()**函式查詢名為**sample.txt**的檔案是否存在,如果我們沒有遇到錯誤,則會在終端列印第一個**Printf()**語句。

輸出

如果我們使用命令**go run main.go**執行上述程式碼,則會在終端得到以下輸出。

File exists

上述方法執行良好,但有一個陷阱。**Stat()**函式返回的**err**可能是由於許可權錯誤或磁碟故障引起的,因此始終建議與**os.Stat()**函式一起使用**isNotExists(err)**函式。

示例2

考慮以下程式碼。

package main
import(
   "fmt"
   "os"
)
func main() {
   if fileExists("sample.txt") {
      fmt.Println("sample file exists")
   } else {
      fmt.Println("sample file does not exist")
   }
}
func fileExists(filename string) bool {
   info, err := os.Stat(filename)
   if os.IsNotExist(err) {
      return false
   }
   return !info.IsDir()
}

輸出

如果我們使用**go run main.go**執行上述程式碼,則會在終端得到以下輸出。

File exists

更新於:2023年11月1日

39K+瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.