【发布时间】:2014-04-11 10:49:38
【问题描述】:
我总是使用with 语句打开和写入文件:
with open('file_path', 'w') as handle:
print >>handle, my_stuff
但是,如果提供的是 而不是 文件路径,我需要能够更加灵活地写入sys.stdout(或其他类型的流):
所以,我的问题是:有没有办法将with 语句同时用于真实文件和sys.stdout?
请注意,我可以使用以下代码,但我认为这违背了使用with 的目的:
if file_path != None:
outputHandle = open(file_path, 'w')
else:
outputHandle = sys.stdout
with outputHandle as handle:
print >>handle, my_stuff
【问题讨论】:
标签: python stream stdout with-statement