循环创建文件时关闭文件

Closing a file when looping creates that file

我正在遍历文本文件 test.fasta 的行,当我到达 format1 行时,我想创建一个 newFile1,跳过一行, 然后将下面的 f 行写入 newFile1 直到我到达另一行 format1 ,此时我想关闭 newFile1,创建 newfile2等等

我目前拥有的:

import re

with open('test.fasta', 'r') as seqs:

    seqFile = (open('throwaway.txt', 'a+'))

    for line in seqs:
        if re.search('^>[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]', line):
            seqFile.close()
            seqFile = open('%s.fasta' % line, 'a+')
            seqs.next()
        else:
            seqFile.write('%s' % line)

    seqFile.close()

此代码有效,输出符合我的预期。问题是,在我开始循环之前,我需要创建那个 throwaway.txt 文件,这样我的循环的第一次迭代就不会因为 seqFile 不存在而失败。如果我不包括 seqFile.close() 它所在的位置,那么我只是让一堆文件处于打开状态。

我可以添加一个 if 语句,它只处理没有打开文件的第一次迭代,但我想知道是否有更优雅的方法来做到这一点。

对我来说,避免依赖虚拟文件存在的最直接方法是在您尝试调用 close:[=12= 时通过循环在第一次捕获该异常]

if re.search('^>[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]', line):
  try:
    seqFile.close()
  except NameError: # Assuming you haven't set seqFile else where before the first time through the loop
    pass
  seqFile = open('%s.fasta' % line, 'a+')
  # Do everything else you were going to do