在 Go 中检查文件是否存在
本文将讨论在 Go 中检查文件是否存在。
在 Go 中使用 IsNotExist()
和 Stat()
检查文件是否存在
我们使用 Go 编程语言中 os
包中的 IsNotExist()
和 Stat()
方法来确定文件是否存在。
Stat()
函数返回一个包含文件信息的对象。如果文件不存在,它会产生一个错误对象。
下面是使用 IsNotExist()
和 Stat()
的代码示例。
示例 1:
package main
import (
"fmt"
"os"
)
// function to check if file exists
func doesFileExist(fileName string) {
_, error := os.Stat(fileName)
// check if error is "file not exists"
if os.IsNotExist(error) {
fmt.Printf("%v file does not exist\n", fileName)
} else {
fmt.Printf("%v file exist\n", fileName)
}
}
func main() {
// check if demo.txt exists
doesFileExist("demo.txt")
// check if demo.csv exists
doesFileExist("demo.csv")
}
输出:
demo.txt file exist
demo.csv file does not exist
示例 2:
package main
import (
"fmt"
"os"
)
func main() {
file_name := "/Usr/sample.go"
if _, err := os.Stat(file_name); err == nil {
fmt.Println("File exists")
} else if os.IsNotExist(err) {
fmt.Println("File or path doesn't exist")
} else {
fmt.Println(err)
}
}
输出:
File or path doesn't exist
相关文章
在 C# 中检查文件是否存在
发布时间:2024/01/16 浏览次数:87 分类:编程语言
-
C# 中的 File.Exists()函数可以用来检查一个文件是否存在于特定路径中。使用 C# 中的 File.Exists(path) 函数检查文件是否存在于特定路径中
如何在 Java 中检查文件是否存在
发布时间:2023/08/14 浏览次数:129 分类:Java
-
本文将介绍 Java 中检查文件是否存在的几种简单方法。当我们想知道指定的文件是否存在时,我们将使用不同的包和类。
使用批处理检查文件是否存在
发布时间:2023/08/15 浏览次数:265 分类:操作系统
-
本文将通过示例代码演示使用批处理脚本检查文件是否存在。使用批处理脚本检查文件是否存在 下面提供了检查文件是否存在的代码的一般格式或语法。
在 Golang 中使用 If-Else 和 Switch Loop Inside HTML 模板
发布时间:2023/04/27 浏览次数:101 分类:Go
-
本篇文章介绍了在 Golang 的 HTML 模板中使用 if-else 和 switch 循环。因此,只要输出是 HTML,就应该始终使用 HTML 模板包而不是文本模板。
Golang 中的零值 Nil
发布时间:2023/04/27 浏览次数:184 分类:Go
-
本篇文章介绍 nil 在 Golang 中的含义,nil 是 Go 编程语言中的零值,是众所周知且重要的预定义标识符。
Golang 中的 Lambda 表达式
发布时间:2023/04/27 浏览次数:691 分类:Go
-
本篇文章介绍如何在 Golang 中创建 lambda 表达式。Lambda 表达式似乎不存在于 Golang 中。 函数文字、lambda 函数或闭包是匿名函数的另一个名称。
在 Go 中捕获 Panics
发布时间:2023/04/27 浏览次数:104 分类:Go
-
像错误一样,Panic 发生在运行时。 换句话说,当您的 Go 程序中出现意外情况导致执行终止时,就会发生 Panics。让我们看一些例子来捕捉 Golang 中的Panics。