我有一个脚本,它接受一组数据,以及根据当时需要的几个不同输出的命令行选项。目前,即使没有任何内容写入文件,该文件也可能是由于使用“with”而创建的。下面的简化代码说明了我的观点。如果使用 -a 和 -b 选项调用程序,则将完全按照我的要求生成具有正确输出的 3 个文件,但如果不需要 a 或 b,则将创建“a.output”和“b.output”文件其中什么也没有。
import argparse
parser = argparse.ArgumentParser(description="description")
parser.add_argument("-a", "--a", action='store_true', default = False, help = "A type analysis")
parser.add_argument("-b", "--b", action='store_true', default = False, help = "b type analysis")
args = parser.parse_args()
master_dictionary = {}
if args.a:
master_dictionary["A"] = A_Function()
if args.b:
master_dictionary["B"] = B_Function()
master_dictionary["default"] = default_Function()
with open("a.output", "w") as A, open("b.output", "w") as B, open("default.output", "w") as default:
for entry in master_dictionary:
print>>entry, printing_format_function(master_dictionary[entry])
我知道我可以折叠打印选项以在条件内的函数调用之后进行,但在实际脚本中事情更加复杂,并且将打印放在分析 block 中不太理想。我想要一个专门修改 with 命令的答案。目标是“a.output”和“b.output”文件仅在包含文本时才会创建。
最佳答案
您无法将创建作为 with
block 的一部分来停止。当您使用 obj 作为 A 时,obj
必须先存在,然后 with
block 才能对其执行任何操作。调用 open('a.output', 'w')
会在 with
对此事有任何发言权之前创建文件。
您可以编写自己的上下文管理器,它会自动删除with
block 末尾的文件,但这不会阻止它在首先, block 内的代码必须以某种方式手动向上下文管理器发出“信号”以进行删除(例如,通过在其上设置某些属性)。
在循环内使用单文件 with
block 可能会更简单。像这样的事情:
for output_file in files_to_create:
with open(output_file, 'w') as f:
# write to the file
其中files_to_create
是您在进入循环之前填充的列表,通过查看您的选项并仅在给出了适当的选项时将文件添加到列表中。然而,正如我在评论中指出的,我认为您尝试处理此循环的方式还存在其他问题,因此很难确切地知道代码应该是什么样子。
关于python - python "with"命令可以用于选择性地写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27068779/