GolangNote

Golang笔记

GoLang 检测文件/文件夹是否存在并自动创建

Permalink

GoLang 检测文件/文件夹是否存在,若不存在则自动创建,常用到的一个功能代码。

Go: 自动创建文件/文件夹
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    fmt.Println("Hello, 世界")
    path := "/tmp/to/create3"

    // check
    if _, err := os.Stat(path); err == nil {
        fmt.Println("path exists 1", path)
    } else {
        fmt.Println("path not exists ", path)
        err := os.MkdirAll(path, 0711)

        if err != nil {
            log.Println("Error creating directory")
            log.Println(err)
            return
        }
    }

    // check again
    if _, err := os.Stat(path); err == nil {
        fmt.Println("path exists 2", path)
    }
}

本文网址: https://golangnote.com/topic/92.html 转摘请注明来源

Related articles

Golang http client 处理重定向网页

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。...

Write a Comment to "GoLang 检测文件/文件夹是否存在并自动创建"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms