How To Create File With Open Function In Python?
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 di
Solution 1:
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.
Solution 2:
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')
Solution 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')
Post a Comment for "How To Create File With Open Function In Python?"