如何检查Go中是否存在文件? [英] How to check if a file exists in Go?

查看:114
本文介绍了如何检查Go中是否存在文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go的标准库没有专门用于检查文件是否存在的功能(如Python的 os.path.exists )。

解决方案

要检查文件是否不存在,请执行惯用 ,相当于Python的如果不是os.path.exists(filename)

  if _,err:= os.Stat(/ path / to / whatever); os.IsNotExist(err){
// path / to / whatever不存在
}

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



_ pre> if _,err:= os.Stat(/ path / to / whatever); !os.IsNotExist(err){
// path / to / whatever 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?

解决方案

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"); os.IsNotExist(err) {
  // path/to/whatever does not exist
}

To check if a file exists, equivalent to Python's if os.path.exists(filename):

if _, err := os.Stat("/path/to/whatever"); !os.IsNotExist(err) {
  // path/to/whatever exists
}

这篇关于如何检查Go中是否存在文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆