This is a creation in Article, where the information may have evolved or changed.
Life goes on and on go Go go!!!
The standard library for Golang has been introduced before: Path/filepath, OS
Go Language Learning Path/filepath Pack (the path to go)
File-related operations in the Go Language learning OS package (the path to go)
Today, we share a few related actions about files and folders.
Get all files in directory
Using packages:
Io/ioutil
How to use:
Ioutil. ReadDir
Read all directories and files in directory Dirmane (not including subdirectories)
Returns the list of information read to the file and any errors encountered during reading
The list of returned files is sorted
FileInfo
typeinterface { string // base name of the file int64 // length in bytes for regular files; system-dependent for others Mode() FileMode // file mode bits // modification time bool // abbreviation for Mode().IsDir() interface{} // underlying data source (can return nil)}
Code:
package mainimport ( "fmt" "io/ioutil")func main() { `d:\go_workspace\` files, _ := ioutil.ReadDir(myfolder) forrange files { if file.IsDir() { continue else { fmt.Println(file.Name()) } }}
Get all files in directory and subdirectories
Based on the above code, use recursion to traverse all folders and subfolders.
Code:
package mainimport ( "fmt" "io/ioutil")func main() { `d:\go_workspace\` listFile(myfolder)}funcstring) { files, _ := ioutil.ReadDir(myfolder) forrange files { if file.IsDir() { "/" + file.Name()) else { "/" + file.Name()) } }}
Get the directory where the execution files are located
Code Listing 1:
Using packages:
Path/filepath
Os
package mainimport ( "fmt" "log" "os" "path/filepath")func main() { dir, err := filepath.Abs(filepath.Dir(os.Args[0])) ifnil { log.Fatal(err) } fmt.Println(dir)}
Code Listing 2:
Using packages:
Path/filepath
Os
package mainimport ( "fmt" "os" "path/filepath")func main() { ex, err := os.Executable() ifnil { panic(err) } exPath := filepath.Dir(ex) fmt.Println(exPath)}
Code Listing 3:
Using packages:
Os
package mainimport ( "fmt" "os")func main() { pwd, err := os.Getwd() ifnil { fmt.Println(err) os.Exit(1) } fmt.Println(pwd)}
Code Listing 4:
Using packages:
Path/filepath
package mainimport ( "fmt" "path/filepath")func main() { fmt.Println(filepath.Abs("./"))}
Code Listing 5:
Third party libraries: Https://github.com/kardianos/osext
package mainimport ( "fmt" "log" "github.com/kardianos/osext")func main() { folderPath, err := osext.ExecutableFolder() ifnil { log.Fatal(err) } fmt.Println(folderPath)}
Show all folders, subfolders, files, sub-files
Using packages:
Path/filepath
Os
package mainimport ( "fmt" "os" "path/filepath")funcstring, f os.FileInfo, err error) error { fmt.Printf("Visited: %s\n", path) returnnil}func main() { `d:\go_workspace\` err := filepath.Walk(root, visit) fmt.Printf("filepath.Walk() returned %v\n", err)}
Get the size of all files and files in a folder
Using packages:
Path/filepath
Os
PackageMainImport("FMT" "OS" "Path/filepath")funcMain () {dirname: ="."+string(filepath. Separator) d, err: = OS. Open (dirname)ifErr! =Nil{FMT. PRINTLN (ERR) OS. Exit(1) }deferD.close () fi, err: = D.readdir( -1)ifErr! =Nil{FMT. PRINTLN (ERR) OS. Exit(1) } for_, Fi: =Rangefi {ifFi. Mode (). Isregular () {fmt. Println (FI. Name (), FI. Size (),"bytes") } }}
Renaming files
package mainimport ( "log" "os")func main() { "./test.txt" "test_new.txt" err := os.Rename(originalPath, newPath) ifnil { log.Fatal(err) }}
Renaming a folder
package mainimport ( "log" "os")func main() { "test" "test_new" err := os.Rename(originalPath, newPath) ifnil { log.Fatal(err) }}
Determine if a file exists
package mainimport ( "fmt" "os")func main() { "test.txt" result := Exists(originalPath) fmt.Println(result)}funcstringbool { ifnil { if os.IsNotExist(err) { returnfalse } } returntrue}
Determine read and Write permissions for a file
PackageMainImport("Log" "OS")funcMain () {//write PermissionFile, err: = OS. OpenFile ("./test.txt", OS. O_wronly,0666)ifErr! =Nil{ifOs. Ispermission (err) {log. Println ("Error:write permission denied.")}}} file. Close ()//read PermissionFile, err = OS. OpenFile ("./test.txt", OS. O_rdonly,0666)ifErr! =Nil{ifOs. Ispermission (err) {log. Println ("Error:read permission denied.")}}} file. Close ()}