如何在filepath中解析用户环境变量

问题描述 投票:1回答:3

Golang在Windows上。尝试使用

os.Open("%userprofile%\\myfile.txt")

获取file path not found和golang并没有将%userprofile%解析为我的C:\users\myusername文件夹。

windows go environment-variables
3个回答
4
投票

要获得文件句柄,并使程序有点便携,请尝试

userprofile := os.Getenv("USERPROFILE")
f, err := os.Open(path.Join(userprofile, "myfile.txt"))

os.Getenv()将读取环境变量,path.Join()将负责正确构建路径(因此无需执行\\)。

你可能也想看看os.Getenv()而不是os.LookupEnv()。这将告诉您您要查找的环境变量是空的还是根本不存在。有关如何使用它来设置默认值的一个很好的例子可以在SO的this答案中找到。


0
投票
userprofile := os.Getenv("USERPROFILE")
os.Open(userprofile+"\\myfile.txt")

-1
投票

看看http://www.golangprograms.com/how-to-set-get-and-list-environment-variables.html

您可以读取'userprofile'环境值,并在将其传递给os.Open之前构建路径

© www.soinside.com 2019 - 2024. All rights reserved.