I have the following code in Python which opens and closes a file in every iteration (using with keyword). In 95 % of iterations the file will be the same, so there's no need to open and close it again. Is it possible to optimize it if this optimization has sense?import sysimport redef createFileName(str, index, number_of_words, suffix):  pattern = re.compile([a-zA-Z]+)  matchList = re.findall(pattern, str)  matchList = [x.lower() for x in matchList]  matchList = matchList[0:number_of_words]  return index + _.join(matchList) + suffixif __name__ == __main__:  d = [(aaa, True), (bbb x yyy aa False), (ccc aa, False), (ddd bbb, True), (eee ddd, False), (fff x a b True)] # this list of tuples is just for illustration, it will be usually much bigger.        fileName = createFileName(d[0][0], 00, 3, .txt)  with open(fileName, a) as f:    f.write(d[0][0] + \n)  i = 1  for x in d[1:]:    if x[1]:      fileName = createFileName(x[0], %02d % i, 3, .txt)      i = i + 1    with open(fileName, a) as f:      f.write(x[0] + \n)
Minimizing open-close scenario
python;performance;file
I think this might actually be one of the few cases, where you don't want to use with with its automatic closing of the file, but do it manually:if __name__ == __main__:    # this list of tuples is just for illustration, it will be usually much bigger.          d = [(aaa, True),         (bbb x yyy aa False),         (ccc aa, False),         (ddd bbb, True),         (eee ddd, False),         (fff x a b True)]    f = None    i = 0    try:        for data, new_file in d:            if new_file or i == 0:                if f:                    f.close()                fileName = createFileName(data, %02d % i, 3, .txt)                f = open(fileName, a)                i += 1            f.write(data + \n)    finally:        if f:            f.close()The try..finally is shamelessly stolen from @MatthiasEttinger's answer to ensure that the file is closed even if the code in-between raises an exception.