我有一个简单的两行代码,我需要将输出写入一个文件。代码如下:
import os,sys
print next(os.walk('/var/lib/tomcat7/webapps/'))[1]
怎么做?
请您参考如下方法:
使用 open() 打开文件的方法,写入write和close如下所示关闭它:
import os,sys
with open('myfile','w') as f:
# note that i've applied str before writing next(...)[1] to file
f.write(str(next(os.walk('/var/lib/tomcat7/webapps/'))[1]))
参见 Reading and Writing Files有关如何在 python 中处理文件的更多信息的教程和 What is the python "with" statement designed for? SO 问题是为了更好地理解 with 语句。
祝你好运!
