如何检查Go中是否存在文件?

本文翻译自:How to check if a file exists in Go?

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 ). Go的标准库没有专门用于检查文件是否存在的函数(如Python的os.path.exists )。 What is the idiomatic way to do it? 这样做的惯用方法是什么?


#1楼

参考:https://stackoom.com/question/qWjM/如何检查Go中是否存在文件


#2楼

To check if a file doesn't exist, equivalent to Python's if not os.path.exists(filename) : 要检查文件是否不存在,等效于Python, 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) : 检查文件是否存在,等效于Python的if os.path.exists(filename)

Edited: per recent comments 编辑:根据最近的评论

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

} else if os.IsNotExist(err) {
  // 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


}

#3楼

You should use the os.Stat() and os.IsNotExist() functions as in the following example: 您应该使用os.Stat()os.IsNotExist()函数,如以下示例所示:

// Exists reports whether the named file or directory exists.
func Exists(name string) bool {
    if _, err := os.Stat(name); err != nil {
        if os.IsNotExist(err) {
            return false
        }
    }
    return true
}

The example is extracted from here . 这个例子是从这里提取的。


#4楼

The example by user11617 is incorrect; user11617示例不正确; it will report that the file exists even in cases where it does not, but there was an error of some other sort. 它会报告该文件存在,即使它没有,但有一些其他类型的错误。

The signature should be Exists(string) (bool, error). 签名应该是Exists(字符串)(bool,错误)。 And then, as it happens, the call sites are no better. 然后,实际上,呼叫站点并没有更好。

The code he wrote would better as: 他写的代码更好:

func Exists(name string) bool {
    _, err := os.Stat(name)
    return !os.IsNotExist(err)
}

But I suggest this instead: 但我建议这样做:

func Exists(name string) (bool, error) {
  _, err := os.Stat(name)
  if os.IsNotExist(err) {
    return false, nil
  }
  return err != nil, err
}

#5楼

Answer by Caleb Spare posted in gonuts mailing list. Caleb Spare的回答发表在gonuts邮件列表中。

[...] It's not actually needed very often and [...] using os.Stat is easy enough for the cases where it is required. [...]实际上并不经常使用,并且使用os.Stat对于需要它的情况os.Stat非常容易。

[...] For instance: if you are going to open the file, there's no reason to check whether it exists first. [...]例如:如果要打开文件,则没有理由先检查它是否存在。 The file could disappear in between checking and opening, and anyway you'll need to check the os.Open error regardless. 检查和打开之间文件可能会消失,无论如何,无论如何你都需要检查os.Open错误。 So you simply call os.IsNotExist(err) after you try to open the file, and deal with its non-existence there (if that requires special handling). 因此,在尝试打开文件后,只需调用os.IsNotExist(err) ,并在那里处理它不存在(如果需要特殊处理)。

[...] You don't need to check for the paths existing at all (and you shouldn't). [...]您根本不需要检查存在的路径(您不应该)。

  • os.MkdirAll works whether or not the paths already exist. 无论路径是否已存在, os.MkdirAll正常工作。 (Also you need to check the error from that call.) (您还需要检查该呼叫的错误。)

  • Instead of using os.Create , you should use os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666) . 您应该使用os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666) ,而不是使用os.Create That way you'll get an error if the file already exists. 这样,如果文件已存在,您将收到错误。 Also this doesn't have a race condition with something else making the file, unlike your version which checks for existence beforehand. 此外,没有其他制作文件的竞争条件,与预先检查存在的版本不同。

Taken from: https://groups.google.com/forum/#!msg/golang-nuts/Ayx-BMNdMFo/4rL8FFHr8v4J 摘自: https//groups.google.com/forum/#! msg / golang-nuts / Ayx-BMNdMFo / 4rL8FFHr8v4J


#6楼

    _, err := os.Stat(file)
    if err == nil {
        log.Printf("file %s exists", file)
    } else if os.IsNotExist(err) {
        log.Printf("file %s not exists", file)
    } else {
        log.Printf("file %s stat error: %v", file, err)
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值