Golang检查是否存在不存在的路径

问题描述 投票:-2回答:1

假设我有一个路径C:\Users\foo\bar,我想检查它是否为目录(在示例中,该路径为目录)。即使目录在磁盘上不存在,在Go中有内置的方法可以做到这一点吗?

go
1个回答
3
投票

您可以使用os.Stat

fi, err:=os.Stat(path)
if err!=nil {
  // Does not exist, or permissions issue, etc.
   pathError:=err.(*os.PathError)
   // get detalils of error if necessary
}  else if fi.IsDir() {
  // Directory
}

您无法检查不存在的路径是否可以是目录。在您的示例中,bar可以是文件或目录。

© www.soinside.com 2019 - 2024. All rights reserved.