How to remove all contents of a directory using Golang?

前端 未结 4 416
灰色年华
灰色年华 2021-01-31 06:58

I\'m new to Go and can\'t seem to find a way to delete all the contents of a directory when I don\'t know the contents.

I\'ve tried:

os.RemoveAll(\"/tmp/         


        
4条回答
  •  难免孤独
    2021-01-31 07:48

    Just use ioutil.ReadDir to get a slice of os.FileInfo types, then iterate through and remove each child item using os.RemoveAll.

    package main
    
    import (
        "io/ioutil"
        "os"
        "path"
    )
    
    func main() {
        dir, err := ioutil.ReadDir("/tmp")
        for _, d := range dir {
            os.RemoveAll(path.Join([]string{"tmp", d.Name()}...))
        }
    }
    

    That way, you are removing only all the child items and not the parent /tmp folder itself.

    I have used this pattern many times before (e.g. test logs, etc.).

提交回复
热议问题