Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create file with open function in Python?

Tags:

python

file

linux

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?

like image 660
alwbtc Avatar asked Dec 02 '22 22:12

alwbtc


1 Answers

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.

like image 151
Ned Batchelder Avatar answered Dec 15 '22 14:12

Ned Batchelder