3

Golang on windows. Trying to use

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

Getting file path not found and golang is not resolving %userprofile% to my C:\users\myusername folder.

1
  • For POSIX shells you can use os.ExpandEnv, but it doesn't seem to support the %VAR% style variables you're using. It would be trivial to implement your own version, though. Commented Mar 28, 2019 at 7:17

4 Answers 4

6

To get a file handle, and make your program a little portable too, try

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

The os.Getenv() will read the environment variable and path.Join() will take care of properly constructing the path (so no need to do \\).

Instead of os.Getenv() you might also want to look at os.LookupEnv(). This will tell you if the environment variable you're looking for is empty or simply not existing. A good example of how you can use that to set default values can be found in this answer on SO.

Sign up to request clarification or add additional context in comments.

Comments

1

Just written a package to do this. Feedback welcome

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

fmt.Println(windowspathenv.Resolve("%USERPROFILE%/Documents")) // C:\Users\YourName\Documents 

Comments

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

Comments

-1

Have a look at http://www.golangprograms.com/how-to-set-get-and-list-environment-variables.html

You can read the 'userprofile' environment value and and build the path before passing it to os.Open

1 Comment

Link is not pointing there any more.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.