This is a creation in Article, where the information may have evolved or changed.
First, determine whether a file or folder exists
golang
Determining whether a file or folder exists can be os.stat()
judged by methods and os.IsExist()
methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
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 }
|
Ii. Recursive creation of folders
Recursive folder to os.MkdirAll()
method:
1
|
func Mkdirall string, perm FileMode) Error
|
The first parameter is the path, and the second is the permission. If the folder does not exist, it is created, and there is no action.
Third, the test code
1 2 3 4 5 6 7 8 9 Ten One A - - the - - - + - + A at - - - - - in - to + - the * $
|
Package main Import ( "OS" "FMT" ) //Determine if a file or folder exists 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(){ //Recursive creation of folders 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 Terminal:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
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 # running program ./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 # Create 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 exists
|