【发布时间】:2016-02-12 18:48:33
【问题描述】:
自从我了解了这个模式,我就一直在使用
with open('myfile.txt','w') as myfile:
with contextlib.redirect_stdout(myfile):
# stuff
print(...) # gets redirected to file
这让我可以使用打印语法(我更喜欢)来写入文件,并且我可以轻松地将其注释掉以打印到屏幕上进行调试。但是,通过这样做,我将无法同时写入文件和屏幕,并且可能会编写不太清晰的代码。还有其他我应该知道的缺点吗?这是我应该使用的模式吗?
【问题讨论】:
标签: python file python-3.x stdout