乐闻世界logo
搜索文章和话题

How to check if a file exists in go

2个答案

1
2

在Go语言中,检查文件是否存在有几种方法,但最常见和简单的方法是使用os.Stat函数和os.IsNotExist函数。下面是一个示例,展示了如何使用这两个函数来检查文件是否存在:

go
package main import ( "fmt" "os" ) // fileExists 检查文件是否存在,返回布尔值和可能出现的错误 func fileExists(filename string) (bool, error) { // 使用os.Stat获取文件信息 info, err := os.Stat(filename) if os.IsNotExist(err) { // 如果返回的错误类型为文件不存在,则说明文件确实不存在 return false, nil } // 如果info不为空,并且没有错误,则文件存在 return !info.IsDir(), err } func main() { // 检查文件"example.txt"是否存在 exists, err := fileExists("example.txt") if err != nil { // 如果有错误,打印错误并退出 fmt.Printf("Failed to check if file exists: %v\n", err) return } // 根据存在标志打印相应的信息 if exists { fmt.Println("File exists.") } else { fmt.Println("File does not exist.") } }

在上述代码中,fileExists函数会尝试获取指定文件的信息。如果os.Stat函数返回一个错误,并且通过os.IsNotExist检查确认这个错误是因为文件不存在,则fileExists会返回false和一个nil错误。如果没有错误,并且info.IsDir()也为false(意味着路径不是一个目录),则函数返回true

需要注意的是,文件可能因为其他原因而无法访问(例如权限问题),此时os.Stat会返回非nil的错误,这种情况下,你可能需要根据具体的错误类型来作出不同的处理。

2024年6月29日 12:07 回复

检查文件是否不存在,相当于Python的if not os.path.exists(filename)

shell
if _, err := os.Stat("/path/to/whatever"); errors.Is(err, os.ErrNotExist) { // path/to/whatever does not exist }

检查文件是否存在,相当于Python的if os.path.exists(filename)

编辑:根据最近的评论

shell
if _, err := os.Stat("/path/to/whatever"); err == nil { // path/to/whatever exists } else if errors.Is(err, os.ErrNotExist) { // path/to/whatever does *not* exist } else { // Schrodinger: file may or may not exist. See err for details. // Therefore, do *NOT* use !os.IsNotExist(err) to test for file existence }
2024年6月29日 12:07 回复

你的答案