输出未重定向到python中的文件

2024-04-19 10:17:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用os.walk()列出/中以“e”开头的所有文件。但是代码似乎没有将输出重定向到文件,而是显示在IDE上。你知道吗

import os, sys

out = sys.stdout
with open('output.txt', 'w') as outfile:
     sys.stdout = outfile
     for root, dirs, files in os.walk('/'):
         for file in files:
             if file.startswith('e'):
                 print file
     sys.stdout = out

谁能告诉我这个代码有什么问题吗。如果可能的话,还有一个更好的方法来完成上述任务。


Tags: 文件代码inimportforosstdoutsys
2条回答

在示例代码中,更改sys.stdout的值不会影响print语句,因为print不直接使用sys.stdout编辑:实际上,这在我的Python解释器中是有效的。但不管怎样,这样做是错误的。你知道吗

要打印到文件,应该在print语句或函数调用中指定文件。在Python 2中,^{}是一个语句,您可以这样指定一个文件:

with open('output.txt', 'w') as outfile:
    print >> outfile, "Hello, world!"

在python3中,^{}是一个带有可选file参数的函数:

with open('output.txt', 'w') as outfile:
    print("Hello, world!", file=outfile)

或者,可以使用open file对象的方法,例如write()

with open('output.txt', 'w') as outfile:
    outfile.write("Hello, world!\n")

对于Python 2:

import os

path = r"/"
outfile = 'output.txt'

with open(outfile, 'w') as fh:
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.startswith('e'):
                print >> fh, file

有关打印的说明,请参阅文档:https://docs.python.org/2/reference/simple_stmts.html#the-print-statement

对于Python 3:

import os

path = r"/"
outfile = 'output.txt'

with open(outfile, 'w') as fh:
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.startswith('e'):
                print(fh, file=outfile)

相关问题 更多 >