如何在 Go 中检查文件是否存在? [英] How to check if a file exists in Go?
本文介绍了如何在 Go 中检查文件是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Go 的标准库没有专门用于检查文件是否存在的函数(如 Python 的 os.path.exists
).惯用的方法是什么?
Go's standard library does not have a function solely intended to check if a file exists or not (like Python's os.path.exists
). What is the idiomatic way to do it?
推荐答案
检查一个文件是否不存在,相当于Python的if not os.path.exists(filename)
:>
To check if a file doesn't exist, equivalent to Python's if not os.path.exists(filename)
:
if _, err := os.Stat("/path/to/whatever"); errors.Is(err, os.ErrNotExist) {
// path/to/whatever does not exist
}
检查文件是否存在,相当于Python的if os.path.exists(filename)
:
To check if a file exists, equivalent to Python's if os.path.exists(filename)
:
已根据最近的评论
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
}
这篇关于如何在 Go 中检查文件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文