[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("存在") } }