关于Windows:如何解析文件路径中的用户环境变量

How to resolve user environment variables in filepath

在Windows上使用Golang。尝试使用

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

获取file path not found和golang不能将%userprofile%解析到我的C:\\users\\myusername文件夹中。


要获取文件句柄并使程序也更易于移植,请尝试

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

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

代替os.Getenv(),您可能还需要查看os.LookupEnv()。这将告诉您要查找的环境变量是否为空或根本不存在。有关如何使用它来设置默认值的一个很好的示例可以在SO的此答案中找到。


只需编写一个程序包即可。欢迎反馈

https://gitlab.com/stu-b-doo/windowspathenv/

1
2
3
fmt.Println(windowspathenv.Resolve("%USERPROFILE%/Documents"))

// C:\\Users\\YourName\\Documents

1
2
userprofile := os.Getenv("USERPROFILE")
os.Open(userprofile+"\\\\myfile.txt")

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

您可以阅读\\'userprofile \\'环境值并在将路径传递给os.Open

之前构建路径