Golang在Windows上。尝试使用
os.Open("%userprofile%\\myfile.txt")
获取file path not found
和golang并没有将%userprofile%
解析为我的C:\users\myusername
文件夹。
要获得文件句柄,并使程序有点便携,请尝试
userprofile := os.Getenv("USERPROFILE")
f, err := os.Open(path.Join(userprofile, "myfile.txt"))
os.Getenv()
将读取环境变量,path.Join()
将负责正确构建路径(因此无需执行\\
)。
你可能也想看看os.Getenv()
而不是os.LookupEnv()
。这将告诉您您要查找的环境变量是空的还是根本不存在。有关如何使用它来设置默认值的一个很好的例子可以在SO的this答案中找到。
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之前构建路径