Go實戰--golang中檔案以及檔案夾路徑相關操作

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

生命不止,繼續 go go go!!!

之前介紹過golang的標準庫:path/filepath, os

Go語言學習之path/filepath包(the way to go)

Go語言學習之os包中檔案相關的操作(The way to go)

今天就跟大家分享幾個關於檔案以及檔案夾的相關操作。

擷取目錄中所有檔案

使用包:
io/ioutil

使用方法:
ioutil.ReadDir
讀取目錄 dirmane 中的所有目錄和檔案(不包括子目錄)
返回讀取到的檔案的資訊列表和讀取過程中遇到的任何錯誤
返回的檔案清單是經過排序的

FileInfo

type FileInfo interface {        Name() string       // base name of the file        Size() int64        // length in bytes for regular files; system-dependent for others        Mode() FileMode     // file mode bits        ModTime() time.Time // modification time        IsDir() bool        // abbreviation for Mode().IsDir()        Sys() interface{}   // underlying data source (can return nil)}

代碼:

package mainimport (    "fmt"    "io/ioutil")func main() {    myfolder := `d:\go_workspace\`    files, _ := ioutil.ReadDir(myfolder)    for _, file := range files {        if file.IsDir() {            continue        } else {            fmt.Println(file.Name())        }    }}

擷取目錄以及子目錄中所有檔案

在上面代碼的基礎上,使用遞迴,遍曆所有的檔案夾和子檔案夾。

代碼:

package mainimport (    "fmt"    "io/ioutil")func main() {    myfolder := `d:\go_workspace\`    listFile(myfolder)}func listFile(myfolder string) {    files, _ := ioutil.ReadDir(myfolder)    for _, file := range files {        if file.IsDir() {            listFile(myfolder + "/" + file.Name())        } else {            fmt.Println(myfolder + "/" + file.Name())        }    }}

擷取執行檔案所在目錄

代碼1:
使用包:
path/filepath
os

package mainimport (    "fmt"    "log"    "os"    "path/filepath")func main() {    dir, err := filepath.Abs(filepath.Dir(os.Args[0]))    if err != nil {        log.Fatal(err)    }    fmt.Println(dir)}

代碼2:
使用包:
path/filepath
os

package mainimport (    "fmt"    "os"    "path/filepath")func main() {    ex, err := os.Executable()    if err != nil {        panic(err)    }    exPath := filepath.Dir(ex)    fmt.Println(exPath)}

代碼3:
使用包:
os

package mainimport (    "fmt"    "os")func main() {    pwd, err := os.Getwd()    if err != nil {        fmt.Println(err)        os.Exit(1)    }    fmt.Println(pwd)}

代碼4:
使用包:
path/filepath

package mainimport (    "fmt"    "path/filepath")func main() {    fmt.Println(filepath.Abs("./"))}

代碼5:
第三方庫:https://github.com/kardianos/osext

package mainimport (    "fmt"    "log"    "github.com/kardianos/osext")func main() {    folderPath, err := osext.ExecutableFolder()    if err != nil {        log.Fatal(err)    }    fmt.Println(folderPath)}

顯示所有檔案夾、子檔案夾、檔案、子檔案

使用包:
path/filepath
os

package mainimport (    "fmt"    "os"    "path/filepath")func visit(path string, f os.FileInfo, err error) error {    fmt.Printf("Visited: %s\n", path)    return nil}func main() {    root := `d:\go_workspace\`    err := filepath.Walk(root, visit)    fmt.Printf("filepath.Walk() returned %v\n", err)}

擷取檔案夾中所有檔案以及檔案的大小

使用包:
path/filepath
os

package mainimport (    "fmt"    "os"    "path/filepath")func main() {    dirname := "." + string(filepath.Separator)    d, err := os.Open(dirname)    if err != nil {        fmt.Println(err)        os.Exit(1)    }    defer d.Close()    fi, err := d.Readdir(-1)    if err != nil {        fmt.Println(err)        os.Exit(1)    }    for _, fi := range fi {        if fi.Mode().IsRegular() {            fmt.Println(fi.Name(), fi.Size(), "bytes")        }    }}

重新命名檔案

package mainimport (    "log"    "os")func main() {    originalPath := "./test.txt"    newPath := "test_new.txt"    err := os.Rename(originalPath, newPath)    if err != nil {        log.Fatal(err)    }}

重新命名檔案夾

package mainimport (    "log"    "os")func main() {    originalPath := "test"    newPath := "test_new"    err := os.Rename(originalPath, newPath)    if err != nil {        log.Fatal(err)    }}

判斷某個檔案是否存在

package mainimport (    "fmt"    "os")func main() {    originalPath := "test.txt"    result := Exists(originalPath)    fmt.Println(result)}func Exists(name string) bool {    if _, err := os.Stat(name); err != nil {        if os.IsNotExist(err) {            return false        }    }    return true}

判斷某個檔案的讀寫權限

package mainimport (    "log"    "os")func main() {    //Write permission    file, err := os.OpenFile("./test.txt", os.O_WRONLY, 0666)    if err != nil {        if os.IsPermission(err) {            log.Println("Error: Write permission denied.")        }    }    file.Close()    //Read permission    file, err = os.OpenFile("./test.txt", os.O_RDONLY, 0666)    if err != nil {        if os.IsPermission(err) {            log.Println("Error: Read permission denied.")        }    }    file.Close()}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.