【问题标题】:Can python "with" command be used to optionally write a filepython“with”命令可以用来选择性地写入文件吗
【发布时间】:2014-11-21 19:23:44
【问题描述】:

我有一个脚本,它接收一组数据,以及几个不同输出的命令行选项,具体取决于当时的需要。目前,即使没有将任何内容写入文件,也可能由于使用了“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])

我知道我可以折叠打印选项以在条件函数调用之后进行,但在实际脚本中,事情更复杂,将打印放在分析块中不太理想。我想要一个专门修改 with 命令的答案。目标是“a.output”和“b.output”文件只有在它们要包含文本时才会被创建。

【问题讨论】:

  • 我不认为你的循环会做你认为它会做的事情。执行for entry in master_dictionary 将遍历字符串"A""B",而不是您创建的名为AB 的文件对象。

标签: python io with-statement


【解决方案1】:

作为with 块的一部分,您无法停止创建。当您执行with obj as A 时,obj 必须在with 块可以对其执行任何操作之前存在。在with 对此事有任何发言权之前,调用open('a.output', 'w') 会创建文件。

可以编写自己的上下文管理器,它会自动删除 with 块末尾的文件,但这不会阻止它首先被创建,并且块内的代码必须以某种方式手动向上下文管理器发出“信号”以进行删除(例如,通过在其上设置一些属性)。

在循环内有一个单一文件with 块可能会更简单。像这样的:

for output_file in files_to_create:
    with open(output_file, 'w') as f:
        # write to the file

其中files_to_create是您在进入循环之前填充的列表,通过查看您的选项并仅在给出适当的选项时将文件添加到列表中。但是,正如我在评论中指出的那样,我认为您尝试处理此循环的方式存在其他问题,因此很难确切知道代码应该是什么样子。

【讨论】:

  • 感谢“with”的解释,这与我的想法一致。我喜欢要创建的东西列表。
  • 如何在没有赞成票的情况下获得接受?但是,为什么人们会回答他们不赞成的问题......
猜你喜欢
  • 2019-05-28
  • 2013-06-11
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-12
  • 2020-08-08
相关资源
最近更新 更多