Home  >  Article  >  Backend Development  >  Golang determines whether the file exists or not and creates the file.

Golang determines whether the file exists or not and creates the file.

尚
Original
2019-12-14 10:45:468721browse

Golang determines whether the file exists or not and creates the file.

1. Determine whether a file or folder exists

golang can determine whether a file or folder exists through the os.stat() method and os.IsExist() method to judge:

func isExist(path string)(bool){
    _, err := os.Stat(path)
    if err != nil{
        if os.IsExist(err){
            return true
        }
        if os.IsNotExist(err){
            return false
        }
        fmt.Println(err)
        return false
    }
    return true
}

2. Recursively create folders

Recursive folders use os.MkdirAll() method:

func MkdirAll(path string, perm FileMode) error

The first parameter is the path, and the second is the permission. If the folder does not exist, create it; if it exists, do nothing.

3. Test code

package main
import (
    "os"
    "fmt"
)
//判断文件或文件夹是否存在
func isExist(path string)(bool){
    _, err := os.Stat(path)
    if err != nil{
        if os.IsExist(err){
            return true
        }
        if os.IsNotExist(err){
            return false
        }
        fmt.Println(err)
        return false
    }
    return true
}
func main(){
    //递归创建文件夹
    err := os.MkdirAll("./test/1/2", os.ModePerm)
    if err != nil{
        fmt.Println(err)
        return
    }
    dirs := []string{"./test/1", "./test/2", "./test/1.txt"}
    for _, v := range dirs{
        if isExist(v){
            fmt.Printf("%s is exist!", v)
        }else{
            fmt.Printf("%s is not exist!", v)
        }
    }
}

Execute in the terminal:

ma@ma:/data/code/go/src/file_exist$ tree
.
└── file_exist.go
0 directories, 1 file
ma@ma:/data/code/go/src/file_exist$ go run file_exist.go  # 运行程序
./test/1 is exist!
./test/2 is not exist!
./test/1.txt is not exist!
ma@ma:/data/code/go/src/file_exist$ tree  
.
├── file_exist.go
└── test
    └── 1
        └── 2
3 directories, 1 file
ma@ma:/data/code/go/src/file_exist$ touch test/1.txt  # 创建1.txt
ma@ma:/data/code/go/src/file_exist$ go run file_exist.go 
./test/1 is exist!
./test/2 is not exist!
./test/1.txt is exist!  # 1.txt存在

For more golang knowledge, please pay attention to the golang tutorial column .

The above is the detailed content of Golang determines whether the file exists or not and creates the file.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn