如何在Python中使用开放函数创建文件? [英] How to create file with open function in Python?
本文介绍了如何在Python中使用开放函数创建文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在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"
我对"$ MYUSER/OUTPUT/myfolder/"目录具有读/写权限.
I have read/write permission do "$MYUSER/OUTPUT/myfolder/" directories.
为什么会出现此错误?为什么不创建mytext.html文件?
Why do I get this error? Why doesn't it create mytext.html file?
推荐答案
os.path.expandvars()
可以帮助:
f = open(os.path.expandvars(HTMLFILE), 'w')
open
仅处理实际的文件名. expandvars
可以在字符串中扩展环境变量.
open
only deals with actual file names. expandvars
can expand environment variables in strings.
这篇关于如何在Python中使用开放函数创建文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文