我有一个脚本接受作为参数的文件名,而不是打开它并写入一些东西。如果没有提供文件名回退到标准输出
我使用with
声明:
with open(file_name, 'w') as out_file:
...
out_file.write(...)
现在,如果我想如果没有提供file_name
写sys.stdout
?
我是否需要将一个函数中的所有动作都包装起来,并在之前放置一个条件?
if file_name is None:
do_everything(sys.stdout)
else:
with open(file_name, 'w') as out_file:
do_everything(out_file)
这似乎很多pythonic :)需要一些'import'我猜 – neurino 2012-03-23 09:29:19
是的,对不起。只需以我喜欢的方式添加'import'语句。随意使用它,不用'as'或'from'。 – glglgl 2012-03-23 09:37:52