2020年8月28日 星期五

[ 常見問題 ] Check If a File Exists Before Using It

 Source From Here

How-To
In this basic example, we check to see if a file exists before interacting with it (otherwise something’s not going to work as expected). We leverage the power of the os standard library and first use the Stat() function, which although it’s usually used to get information about a file, we’re only looking at the errors.

We can’t just check for err == nil because any number of errors could be returned so we pass it to IsNotExists() to confirm that it’s an error because the file does not exist:
  1. package main  
  2.   
  3. import (  
  4.     "fmt"  
  5.     "os"  
  6. )  
  7.   
  8. func main() {  
  9.     if fileExists("example.txt") {  
  10.         fmt.Println("Example file exists")  
  11.     } else {  
  12.         fmt.Println("Example file does not exist (or is a directory)")  
  13.     }  
  14. }  
  15.   
  16. // fileExists checks if a file exists and is not a directory before we  
  17. // try using it to prevent further errors.  
  18. func fileExists(filename string) bool {  
  19.     info, err := os.Stat(filename)  
  20.     if os.IsNotExist(err) {  
  21.         return false  
  22.     }  
  23.     return !info.IsDir()  
  24. }  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...