使用最少的cod将结果写入文件

2024-04-18 23:42:45 发布

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

我已经为我的事业编写了代码,并在终端中显示结果:

print 'The following results are found:'
# some code iterations here
...
...
print 'User - {0}, Title - {1}'.format(...)

目前,我正在尝试实现一个新的可选参数,它允许我选择是否将上述结果写入文本文件。你知道吗

虽然我可以让它工作,但它不是用最优雅的方法:

# output_to_path is a boolean argument here.

if output_to_file:
    # file_path, I use `open(file_dir, "w")`
    print >> file_path, 'The following results are found:'
print 'The following results are found:'
# some code iterations here
...
...
if output_to_file:
    print 'User - {0}, Title - {1}'.format(...)
print 'User - {0}, Title - {1}'.format(...)

不管output_to_file是真是假,上面的print语句是否只能写一次?我问,因为我有大量的打印声明开始。你知道吗


Tags: thetopathformatoutputheretitlesome
2条回答

这里有一种用context manager实现的方法,类似于我在问题下面的评论中提到的question的答案。你知道吗

关键在于,为了能够根据需要有选择地打开和关闭对文件的输出,最简单的方法似乎是将其实现为class(而不是像这里那样将contextlib@contextmanager修饰符应用于函数)。你知道吗

希望这不是太多的代码。。。你知道吗

import sys

class OutputManager(object):
    """ Context manager that controls whether sysout goes only to the interpreter's
        current stdout stream or to both it and a given file.
    """
    def __init__(self, filename, mode='wt'):
        self.output_to_file = True
        self.saved_stdout = sys.stdout
        self.file = open(filename, mode)
        sys.stdout = self

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        sys.stdout = self.saved_stdout  # Restore.
        self.file.close()

    def write(self, message):
        self.saved_stdout.write(message)
        if self.output_to_file:
            self.file.write(message)

    def enable(self):
        self.output_to_file = True

    def disable(self):
        self.output_to_file = False


if __name__ == '__main__':
    # Sample usage.
    with OutputManager('cmtest.txt') as output_manager:
        print 'This line goes to both destinations.'
        output_manager.disable()
        print 'This line goes only to the display/console/terminal.'
        output_manager.enable()
        print 'Once again, to both destinations.'

你可以写一个函数来做你想做的:

def custom_print(message):
    print(message) # always prints to stdout
    if output_to_file:
        print >> file_path, message

然后你这样称呼它:

custom_print('The following results are found:')
...
custom_print('User - {0}, Title - {1}'.format(...))

相关问题 更多 >