【问题标题】:Writing output of conditional statements to a file within nested loop python将条件语句的输出写入嵌套循环python中的文件
【发布时间】:2019-05-04 13:20:39
【问题描述】:

我有一个 with 循环,我在其中打开两个 json 文件并在我的循环中进行特定比较。我有各种条件语句,根据满足哪个条件,我想将结果输出到文件中。现在我不确定它在 for 循环中的位置。我目前在我的循环中有打印语句,它连接字符串和变量。我想将其替换为写入文件。

with open('file1.json', 'r') as f, open('file2.json', 'r') as g:
    for cd, pd in zip(f, g):
        if condition:  
            if condition:
                print "I would like to output this to a file":
            else: 
                print "I would like to output this to a file"
        else:  # file names do not match
            print "I would like to output this , str(variable)"

【问题讨论】:

  • 我删除了python-3.x标签,因为您使用的是打印语句,这意味着您不能使用Python 3。请不要标记不相关的版本。
  • 没问题@khelwood
  • 那么问题出在哪里?为什么不能直接写入文件而不是使用print
  • h.write("This is being written to a file\n")
  • 您需要使用串联:h.write("File" + str(current_fn) + "with file size" ...)。或者使用格式化运算符使其更易于阅读。

标签: python python-2.7 file while-loop


【解决方案1】:

您的问题似乎只是如何动态构建字符串以便将其写入文件。有(至少)两种基本方法可以做到这一点:

  • 连接字符串的各个部分:

    text = "File: " + str(current_fn) + ", line: " + str(line_number)

  • 使用字符串格式:

    text = "File: {}, line: {}".format(current_fn, line_number)(新式)或

    text = "File: %s, line: %s" % (current_fn, line_number)(旧式)或

    text = "File: {filename}, line: {line_number}".format(filename=current_fn, line_number=line_number)(带有命名插值的新型)

您还可以使用带有旧式格式的命名参数,如果您使用 Python 3 而不是 Python 2,您也可以使用 f-strings。

然后,当然要写消息: h.write(text) 如果h 是一个打开的可写文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-26
    • 2017-12-20
    • 2015-08-02
    • 2019-11-07
    • 1970-01-01
    • 2011-04-23
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多