[Go] 写文件和判断文件是否存在

  • 2019 年 11 月 22 日
  • 筆記

OpenFile得到一个File,然后调用它的Write,参数是字节切片 Stat看看返回错误没有

package main    import (      "fmt"      "os"  )    func main() {      file := "1.txt"      f, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE, 0766)      f.Write([]byte("你好"))      f.Close()        //判断文件是否存在      _, err := os.Stat(file)      if err != nil && os.IsNotExist(err) {          //存在          fmt.Println("不存在")      } else {          fmt.Println("存在")      }  }