golang判断目录是否存在
在Go中,可以使用os.Stat()函数来判断目录是否存在。os.Stat()函数返回一个os.FileInfo类型的值,如果目录存在,则可以通过调用os.IsExist()方法来判断。
以下是一个示例代码:
package main
import (
"fmt"
"os"
)
func main() {
dirPath := "/path/to/directory"
_, err := os.Stat(dirPath)
if err == nil {
fmt.Printf("目录 %s 存在\n", dirPath)
} else if os.IsNotExist(err) {
fmt.Printf("目录 %s 不存在\n", dirPath)
} else {
fmt.Printf("发生错误:%v\n", err)
}
}
在上述代码中,首先使用os.Stat()函数检查目录的存在性。如果没有发生错误,则目录存在。如果返回的错误是os.IsNotExist()函数返回true,则目录不存在。否则,可能是其他错误,需要进一步处理。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/isit 著作权归作者所有。请勿转载和采集!