在条件

时间:2016-10-20 16:53:20

标签: python file

我有一个for循环,里面是一个条件。 如果条件成立,我想创建一个具有特定名称的文件并写入它。如果条件不成立,我只想写入以前迭代中创建的文件。

文件名取决于x [0]。

我还没有运行它,因为很明显它不会运行。您将如何处理有条件的关闭和打开文件(总是使用新名称)?

for x in dd:
  if x[1]: # close old file and start to write to new file
     ...
     f.close() # close the file (will not work in first iteration)
     fileName = "_".join(matchList) # create sensible file name
     f = open(fileName, "w")
     f.write(x[0])
  else:
    f.write(x[0])

2 个答案:

答案 0 :(得分:2)

my_file = something_that_creates_the_first_file()

for x in dd:
    if x[1]:  # Close old file and start to write to new file
        my_file.close()
        fileName = "_".join(matchList) # create sensible file name
        my_file = open(fileName, "w")

    my_file.write(x[0])

my_file.close()

或者,您可以在每次循环迭代时打开和关闭文件,在这种情况下您可以执行以下操作:

fileName = something_that_creates_the_first_file_name()

for x in dd:
    if x[1]:  # Close old file and start to write to new file
        fileName = "_".join(matchList) # create sensible file name

    with open(fileName, "a") as my_file:
        my_file.write(x[0])

后一种方法使用文件的内置上下文管理处理程序来确保是否存在任何错误,从不会打开文件。

答案 1 :(得分:1)

This is @tomdalton's answer with a slight update to add a try/finally block. His should remain the accepted answer, I'm just adding an error management tweak. with clauses are great but only work when the resource should be managed in the clause. Otherwise, you need to fall back to a basic finally block.

my_file = something_that_creates_the_first_file()
try:
    for x in dd:
        if x[1]:  # Close old file and start to write to new file
            my_file.close()
            fileName = "_".join(matchList) # create sensible file name
            my_file = open(fileName, "w")

        my_file.write(x[0])
finally:
    my_file.close()