如何在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)**函数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例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+浏览量

启动您的职业生涯

完成课程获得认证

开始学习
广告