4

In Linux environment, I want to create a file and write text into it:

HTMLFILE: "$MYUSER/OUTPUT/myfolder/mytext.html"
f = open(HTMLFILE, 'w')

IOError: [Errno 2] No such file or directory: "$MYUSER/OUTPUT/myfolder/mytext.html"

I have read/write permission do "$MYUSER/OUTPUT/myfolder/" directories.

Why do I get this error? Why doesn't it create mytext.html file?

3 Answers 3

10

os.path.expandvars() can help:

f = open(os.path.expandvars(HTMLFILE), 'w')

open only deals with actual file names. expandvars can expand environment variables in strings.

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

Comments

5

There are two ways. Using os.environ() to get variable value

HTML_PATH = "/OUTPUT/myfolder/mytext.html"
f = open(os.environ('MYUSER') + HTMLFILE, 'w')

and using os.path.expandvars():

HTMLFILE = "$MYUSER/OUTPUT/myfolder/mytext.html"
f = open(os.path.expandvars(HTMLFILE), 'w')

Comments

3

$MYUSER refers to a shell variable. Python does not resolve those. Use the os package to get the users home directory through os.getenv('MYUSER')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.