SoFunction
Updated on 2025-03-05

Golang creates a file directory, the difference description

As shown below:

 ("abc", )  //Create a directory ("dir1/dir2/dir3", ) //Create multi-level directory 

First, try to create a set of nested directories (such as 'dir1/dir2/dir3') from a Go executable and print the error out to see.

err:=(“dir1/dir2/dir3”,)
if err!=nil{
 (err) 
}
result:mkdir ./dir1/dir2/dir3: The system cannot find the path specified.

Mkdir is used to create a single directory.

err:=("./dir1",)
if err!=nil{
 (err)
}

Successfully created dir1 for the first time. When dir1 is created again, if the path is already a directory, Mkdir will report an error.

mkdir ./dir1: Cannot create a file when that file already exists.

Create folders based on date

import (
 "os"
 "path/filepath"
 "time"
)
// CreateDateDir Create folders based on the current datefunc CreateDateDir(Path string) string {
 folderName := ().Format("20060102")
 folderPath := (Path, folderName)
 if _, err := (folderPath); (err) {
 // It must be divided into two steps: create a folder first, then modify permissions (folderPath, 0777) //0777 is OK (folderPath, 0777)
 }
 return folderPath
}

To create a folder path, please use (folderPath,)

err=("./dir1/dir2",)
if err!=nil{
 (err)
 }
errfornil
Created successfullydir1/dir2File path

MkdirAll will create a directory named path and any necessary parent and return nil, otherwise return an error. The license bit perm is used for all directories created by MkdirAll. If the path is already a directory, MkdirAll does nothing and returns nil.

Create folder paths based on date

uploadDir := "static/upload/" + ().Format("2006/01/02/")
err := ( uploadDir , 777)

Some common functions in other Os packages:

() //Get the current directory

Create a file

f1, _ := ("./") 
defer ()

Open the file in a read-write manner, and create the file if it does not exist, which is equivalent to the above

f4, _ := ("./", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
defer ()

When using () to connect two filename addresses, for example

("D:\","") \\turn outD:\

Delete all files in the specified directory

("abc/d/e/f")

Delete the specified directory

("abc")

Rename the file

("./", "./2_new.txt")

If there is any wrong, please correct me, learn from each other and make progress together.

Supplement: Go creates files with directories

I won't say much nonsense, let's just read the code~

// create file with dir if dir is not exist
// path is dir
// name is file name
func createFileWithDir(path string, name string, content string) {
 (path, )
 file, _ := (path + "/" + name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
 defer ()
 (content)
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.