【问题标题】:golang save file to desktopgolang 保存文件到桌面
【发布时间】:2019-12-11 01:17:03
【问题描述】:

我正在尝试将文件保存到我的桌面,但是每当我运行我的脚本时,它都会将文件保存在 go 脚本所在的任何目录中。

这是我正在使用的代码块

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...\n", 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)
    }
}

我试过路径

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

我似乎无法将文件保存到桌面,例如当我尝试时

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

创建了一个目录~,在~ 内部创建了桌面,在桌面内部创建了 d.dir,所有文件都在其中。同样,我想运行脚本,无论我在哪里运行它,我都想将其内容放在 d.dir 文件夹中,以便在桌面上创建。

【问题讨论】:

    标签: go path


    【解决方案1】:

    您可以使用此功能找到当前用户个人资料 - https://godoc.org/os/user#Current

    因此,根据您的操作系统,桌面将位于主目录的相应文件夹中。

    类似的东西

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

    另外值得注意的是,有一个github.com/mitchellh/go-homedir 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. 的库 因此使用它可以更好地使您的程序更具可移植性。

    【讨论】:

    • 太棒了,谢谢。我还在学习核心库。我一直在使用 python。
    • @msanti,并不是说这会在将来的某些 Windows 版本中中断,因为它将决定将“桌面”重命名为其他名称。真正的方法是使用 Windows shell 集成 API 的“特殊文件夹”工具来获取运行程序的 Windows 上桌面文件夹的位置。不幸的是,这需要 C、Windows API 和从 Go 调用它的某些技能(后者很容易)。我会在go-nuts mailing list 上提问。
    • 哦,没关系。我是 Linux、Unix 用户,这就是这个脚本将保留的地方 lol
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    相关资源
    最近更新 更多