我已经为我的事业编写了代码,并在终端中显示结果:
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语句是否只能写一次?我问,因为我有大量的打印声明开始。你知道吗
这里有一种用context manager实现的方法,类似于我在问题下面的评论中提到的question的答案。你知道吗
关键在于,为了能够根据需要有选择地打开和关闭对文件的输出,最简单的方法似乎是将其实现为
class
(而不是像这里那样将contextlib
的@contextmanager
修饰符应用于函数)。你知道吗希望这不是太多的代码。。。你知道吗
你可以写一个函数来做你想做的:
然后你这样称呼它:
相关问题 更多 >
编程相关推荐