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!

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Developers should follow the following best practices: 1. Carefully manage goroutines to prevent resource leakage; 2. Use channels for synchronization, but avoid overuse; 3. Explicitly handle errors in concurrent programs; 4. Understand GOMAXPROCS to optimize performance. These practices are crucial for efficient and robust software development because they ensure effective management of resources, proper synchronization implementation, proper error handling, and performance optimization, thereby improving software efficiency and maintainability.

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

We need to customize the error type because the standard error interface provides limited information, and custom types can add more context and structured information. 1) Custom error types can contain error codes, locations, context data, etc., 2) Improve debugging efficiency and user experience, 3) But attention should be paid to its complexity and maintenance costs.

Goisidealforbuildingscalablesystemsduetoitssimplicity,efficiency,andbuilt-inconcurrencysupport.1)Go'scleansyntaxandminimalisticdesignenhanceproductivityandreduceerrors.2)Itsgoroutinesandchannelsenableefficientconcurrentprogramming,distributingworkloa

InitfunctionsinGorunautomaticallybeforemain()andareusefulforsettingupenvironmentsandinitializingvariables.Usethemforsimpletasks,avoidsideeffects,andbecautiouswithtestingandloggingtomaintaincodeclarityandtestability.

Goinitializespackagesintheordertheyareimported,thenexecutesinitfunctionswithinapackageintheirdefinitionorder,andfilenamesdeterminetheorderacrossmultiplefiles.Thisprocesscanbeinfluencedbydependenciesbetweenpackages,whichmayleadtocomplexinitializations


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor
