duanbi3385 2015-12-19 02:00 采纳率: 100%
浏览 116
已采纳

golang将文件保存到桌面

I'm trying to saving files to my desktop, however whenever I run my script it saves the file in whatever directory the go script is located in.

This is the chunk of code i'm working with

func (d *downloader) downloadToFile(key string) {
    // Create the directories in the path
    // desktop path
    desktop := "Desktop/" + d.dir
    file := filepath.Join(desktop, key)
    if err := os.MkdirAll(filepath.Dir(file), 0775); err != nil {
        panic(err)
    }

    // Setup the local file
    fd, err := os.Create(file)
    if err != nil {
        panic(err)
    }
    defer fd.Close()

    // Download the file using the AWS SDK
    fmt.Printf("Downloading s3://%s/%s to %s...
", d.bucket, key, file)
    params := &s3.GetObjectInput{Bucket: &d.bucket, Key: &key}
    d.Download(fd, params)
    _, e := d.Download(fd, params)
    if e != nil {
        panic(e)
    }
}

I've tried the path

desktop := "Desktop/" + d.dir
desktop := "/Desktop/" + d.dir
desktop := "Desktop/" + d.dir
desktop := "~/Desktop/ + d.dir

I can't seem to get the files to save to the desktop, for instance when i tried

desktop := "~/Desktop/ + d.dir

A directory ~ was created, inside of ~ Desktop was created, inside of Desktop the d.dir was created, and in there all the files. Again I want to run the script an no matter where I run it I want to d.dir folder with it's contents so be created on the desktop.

  • 写回答

1条回答 默认 最新

  • dpt62283 2015-12-19 02:07
    关注

    You can find current user profile using this function - https://godoc.org/os/user#Current

    So, depending on your OS, desktop will be in corresponding folder in home directory.

    something like this

       myself, error := user.Current()
       if error != nill {
         panic(error)
       }
       homedir := myself.HomeDir
       desktop := homedir+"/Desktop/" + d.dir
    

    also it is worth notice, that there is a github.com/mitchellh/go-homedir library that is a Go library for detecting the user's home directory without the use of cgo, so the library can be used in cross-compilation environments. So using it can be better to make your program more portable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真