如何将 os.walk 的输出写入文件

How to write the output of a os.walk to file

我有一个简单的两行代码,我需要将输出写入一个文件。代码如下:

import os,sys
print next(os.walk('/var/lib/tomcat7/webapps/'))[1]

怎么做?

使用 open() method to open file, write to write to it and 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 tutorial for more information of how to deal with files in python and What is the python "with" statement designed for? SO 问题以更好地理解 with 语句。

祝你好运!

在Python3中你可以使用file参数给print()函数:

import os

with open('outfile', 'w') as outfile:
    print(next(os.walk('/var/lib/tomcat7/webapps/'))[1], file=outfile)

省去转换成字符串的麻烦,而且在输出后还加了一个新行。

如果您在 python 文件的顶部添加此导​​入,则在 Python 2 中同样有效:

from __future__ import print_function

同样在Python2中你可以使用"print chevron"语法(即如果你不添加上面的import):

with open('outfile', 'w') as outfile:
    print >>outfile, next(os.walk('/var/lib/tomcat7/webapps/'))[1]

使用 print >> 还会在每次打印的末尾添加一个新行。

在任一 Python 版本中,您都可以使用 file.write():

with open('outfile', 'w') as outfile:
    outfile.write('{!r}\n'.format(next(os.walk('/var/lib/tomcat7/webapps/'))[1]))

这需要您显式转换为字符串并显式添加新行。

我认为第一个选项最好。