我有可自定义的脚本,可以根据请求提供最多 3 个不同的输出文件。目前我有:
with open("option1", "w") as file1, open("option2", "w") as file2, open("option3", "w") as file3:
我遇到的问题是,如果未选择该选项,文件仍在创建(由于 open 语句),这是我想避免的。
我天真地认为我想要的是允许的语法,如下所示:
with (if type1: open("option1", "w") as file1), (if type2: open("option2", "w") as file2), (if type3: open("option3", "w") as file3):
这 3 种不同的类型和相应的选项并不相互排斥,通常需要一种以上的文件类型。 type1、type2 和 type3 变量是默认设置为 False 的 bool 值,并在命令行中独立切换为 True。总的来说,我正在努力有效地避免创建空文件,并且愿意接受甚至相当剧烈的代码更改来完成它。
最佳答案
filenames_map = {"type1":"option1", "type2":"option2", "type3":"option3"}
filename = filenames_map.get(type, "default_option")
with open(filname, "w") as targetFile:
# do whatever needs to be done
dict.get
从字典中获取值并默认为未找到此类键的第二个参数。
如果类型不是互斥的,那就有点棘手了。 with
是一个复合语句,所以在正常的执行流程下(没有异常(exception))这两个大致等价:
with (context_manager) as something:
do_stuff()
try:
context_manager.__enter__()
do_stuff()
finally:
context_manager.__exit__()
因此,如果您在运行时之前无法确定要写入的文件数量,则必须自己管理上下文。幸运的是,open
返回 FileObject
,这是定义了 __enter__
和 __exit__
的上下文管理器。幸运的是,open
返回 FileObject
这是一个非常简单的上下文管理器。如 documentation 中所述
with open("hello.txt") as f:
for line in f:
print line,
等于
f = open("hello.txt")
try:
for line in f:
print line,
finally:
f.close()
进入正题
target_files = []
# please modify to follow PEP-8 yourself, compressed for clarity
if user_wants_type1(type): target_files.append("option1")
if user_wants_type2(type): target_files.append("option2")
if user_wants_type3(type): target_files.append("option3")
try:
handles = [open(filename) for filename in taget_files]
for handle in handles:
handle.write("something")
finally:
for handle in handles:
handle.close()
关于python - 有条件地写入不同的输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24939174/