search
HomeBackend DevelopmentGolangGolang determines whether the file exists or not and creates the file.

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
init Functions and Side Effects: Balancing Initialization with Maintainabilityinit Functions and Side Effects: Balancing Initialization with MaintainabilityApr 26, 2025 am 12:23 AM

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

Getting Started with Go: A Beginner's GuideGetting Started with Go: A Beginner's GuideApr 26, 2025 am 12:21 AM

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

Go Concurrency Patterns: Best Practices for DevelopersGo Concurrency Patterns: Best Practices for DevelopersApr 26, 2025 am 12:20 AM

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.

Go in Production: Real-World Use Cases and ExamplesGo in Production: Real-World Use Cases and ExamplesApr 26, 2025 am 12:18 AM

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

Custom Error Types in Go: Providing Detailed Error InformationCustom Error Types in Go: Providing Detailed Error InformationApr 26, 2025 am 12:09 AM

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.

Building Scalable Systems with the Go Programming LanguageBuilding Scalable Systems with the Go Programming LanguageApr 25, 2025 am 12:19 AM

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

Best Practices for Using init Functions Effectively in GoBest Practices for Using init Functions Effectively in GoApr 25, 2025 am 12:18 AM

InitfunctionsinGorunautomaticallybeforemain()andareusefulforsettingupenvironmentsandinitializingvariables.Usethemforsimpletasks,avoidsideeffects,andbecautiouswithtestingandloggingtomaintaincodeclarityandtestability.

The Execution Order of init Functions in Go PackagesThe Execution Order of init Functions in Go PackagesApr 25, 2025 am 12:14 AM

Goinitializespackagesintheordertheyareimported,thenexecutesinitfunctionswithinapackageintheirdefinitionorder,andfilenamesdeterminetheorderacrossmultiplefiles.Thisprocesscanbeinfluencedbydependenciesbetweenpackages,whichmayleadtocomplexinitializations

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

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

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor